[LeetCode] 35. Search Insert Position

Posted C·Moriarty

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
    }
}

 

以上是关于[LeetCode] 35. Search Insert Position的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]Binary Search-35. Search Insert Position

LeetCode 35. Search Insert Position

[Binary Search] Leetcode 35, 74

LeetCode OJ 35. Search Insert Position

[LeetCode]35. Search Insert Position

Leetcode-35 Search Insert Position