leetcode

来源:互联网 发布:初中语文老师知乎 编辑:程序博客网 时间:2024/05/14 16:53

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

Solution1:

  public int searchInsert(int[] nums, int target) {    int result = 0;    while (result < nums.length && nums[result] < target) {      result++;    }    return result;  }

Solution2:

  public int searchInsert(int[] nums, int target) {    int begin = 0;    int end = nums.length - 1;    int result;    while (begin <= end) {      result = (begin + end) / 2;      if (nums[result] > target) {        end = result - 1;      } else if (nums[result] == target) {        return result;      } else {        begin = result + 1;      }    }    return begin;  }
0 0