[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

解法一

思路

直接遍历一次数组即可,如果目标值小于等于当前位置的值,直接返回下标即可,当一遍循环结束的时候,还没有返回,说明目标值比数组中的所有值都大,此时直接返回数组长度即可。时间复杂度为O(n)。

代码

class Solution {
    public int searchInsert(int[] nums, int target) {
        for(int i = 0; i < nums.length; i++) {
            if(target <= nums[i])
                return i;
        }
        return nums.length;
    }
}

解法二

思路

用二分法的思路,时间复杂度为O(log2n)。

代码

class Solution {
    public int searchInsert(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while(low <= high) {
            int mid = (low+high)/2;
            if(target == nums[mid]) return mid;
            else if (target < nums[mid]) high = mid - 1;
            else low = mid + 1;       
        }
        return low;
    }
}

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9727900.html