在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

[LintCode/LeetCode] Search Insert Position

2016-8-16 12:47| 发布者: zhangjf| 查看: 682| 评论: 0

摘要: Problem Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume NO duplicates in the a ...
Problem

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume NO duplicates in the array.

Example
  1. [1,3,5,6], 5 → 2
  2. [1,3,5,6], 2 → 1
  3. [1,3,5,6], 7 → 4
  4. [1,3,5,6], 0 → 0
复制代码
Challenge

O(log(n)) time

Note

标准二分法题目。

Solution
  1. public class Solution {
  2. public int searchInsert(int[] A, int target) {
  3. int start = 0, end = A.length-1, mid;
  4. if (A == null || A.length == 0) return 0;
  5. while (start <= end) {
  6. mid = (start+end)/2;
  7. if (A[mid] == target) return mid;
  8. else if (A[mid] < target) start = mid+1;
  9. else end = mid-1;
  10. }
  11. return start;
  12. }
  13. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 16:07

Copyright 2015-2025 djqfx

返回顶部