LeetCode: 35. Search Insert Position

来源:互联网 发布:网易uu加速器mac版 编辑:程序博客网 时间:2024/06/05 04:50

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.

Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7
→ 4 [1,3,5,6], 0 → 0

自己的答案,6ms:

public class Solution {    public int searchInsert(int[] nums, int target) {        if (nums == null) {            return 0;        }        int l = 0, r = nums.length - 1;        return search(nums, target, l, r);    }    private int search(int[] nums, int target, int l, int r) {        if (target <= nums[l]) {            return l;        }        if (target > nums[r]) {            return r + 1;        }        if (l + 1 == r) {            return r;        }        int mid = (l + r) / 2;        if (nums[mid] == target) {            return mid;        } else if (nums[mid] < target) {            l = mid;        } else {            r = mid;        }        return search(nums, target, l, r);    }}

最快的答案,4ms

public class Solution {    public int searchInsert(int[] nums, int target) {        int left = 0;        int right = nums.length - 1;        if(nums == null || nums.length == 0) return -1;        int mid = 0;        while(left <= right){            mid = (left + right) / 2;            if(nums[mid] < target)                left = mid + 1;            else if(target == nums[mid])                return mid;            else                right = mid - 1;        }        return left;    }}
原创粉丝点击