您的位置:首页 > 其它

LeetCode【35】Search Insert Position

2017-12-04 13:14 344 查看
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.

给你一个排好序的数组和一个target,如果数组中有一个和target相等的则返回该数的索引,没有则返回该插入地方的索引

思想:很典型的二分查找,根据中间值大小分成两个区间进行查找,比较简单的题目,直接上代码了解下就好了

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

public static int Sip(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target)
return mid;
if (nums[mid] < target)
l = mid + 1;
else
r = mid - 1;
}
return l;
}

public static void main(String[] args) {
int[] nums = new int[]{2, 3, 5, 7, 8};
int target = 4;
System.out.println(Sip(nums, target));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: