[LeetCode] 35. Search Insert Position

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:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

题意:给一个已经排好序的数组 和一个待查找的数。要求找到这个数所在的位置,如果不存在,返回它应该存在的位置
二分查找(说来惭愧,本人二分查找经常出错,所以当数组小于5的时候我都是采用扫描了,并不是很影响性能)
class Solution {
    public int searchInsert(int[] nums, int target) {
        int i = 0;
        int j = nums.length - 1;
        int index = -1;
        while (j - i > 5) {
            int mid = (i + j) / 2;
            if (nums[mid] > target) {
                j = mid;
            }
            else if (nums[mid] < target) {
                i = mid;
            }
            else {
                index = mid;
                break;
            }
        }
        for (int k = i; k <= j; k++) {
            if (nums[k] == target) {
                index = k;
                break;
            }
            if (k < j && nums[k] < target && nums[k + 1] > target) {
                index = k + 1;
                break;
            }
        }
        if (nums[0] > target)
            index = 0;
        if (nums[nums.length - 1] < target)
            index = nums.length;
        return index;
    }
}

 

posted @ 2018-10-15 21:39  C`Moriarty  阅读(103)  评论(0编辑  收藏  举报
/* 鼠标点击求赞文字特效 */ /*鼠标跟随效果*/