首页 > 其他 > 详细

[LeetCode] 35. Search Insert Position

时间:2018-10-15 22:23:30      阅读:161      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/Moriarty-cx/p/9794916.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!