LeetCode Search Insert Position

来源:互联网 发布:自动化编程软件有哪些 编辑:程序博客网 时间:2024/06/06 00:03

Description:

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.

Solution:

This problem is similar to its former one.

But only get minimum number which is bigger than or equal to target is required.

Pay attention to the condition that target is smialler than nums[0] or greater than nums[length()-1].

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


0 0
原创粉丝点击