【LeetCode】35.Search Insert Position解题报告
tags: Array
题目地址:https://leetcode.com/problems/search-insert-position/tabs/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.
You may assume no duplicates in the array.
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
Solutions:
public class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0, high = nums.length;
while(low<high) {
int mid=low+(high-low)/2; // low<=mid, mid<high
if (nums[mid]>=target) high=mid; // high always decreases (even high-low==1)
else low=mid+1; // low always increases
}
return low;
}
}
仍然不是很理解,mid为小数时该怎么办。
Date:2017年7月29日