leetcode--search_insert_position
2016-11-19 22:11
302 查看
题意: 给定一个排好序的数组以及一个目标值,如果找到该值就返回它在数组中的索引,如果没找到,返回这个值应该被插入位置的索引。数组中没有重复值。
例子:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
分析: 本题使用二分搜索,如果能找到该值,就返回索引;如果没找到该值,则比较当前位置的值和目标值大小,如果当前位置值大于等于目标值,则返回当前位置索引; 如果小于,则返回当前索引加1。
代码
源程序下载
例子:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
分析: 本题使用二分搜索,如果能找到该值,就返回索引;如果没找到该值,则比较当前位置的值和目标值大小,如果当前位置值大于等于目标值,则返回当前位置索引; 如果小于,则返回当前索引加1。
代码
public int searchInsert(int[] A, int target) { return binarySearch(A, 0, A.length - 1, target); } public int binarySearch(int[] A, int begin, int end, int target){ if(begin >= end){ int mid = (begin + end) / 2; if(A[mid] >= target) return mid; else return mid + 1; }else{ int mid = (begin + end) / 2; if(A[mid] == target) return mid; else if(A[mid] > target) return binarySearch(A, begin, mid - 1, target); else return binarySearch(A, mid + 1, end, target); } }
源程序下载
相关文章推荐
- Leetcode 35 Search Insert Position 二分查找(二分下标)
- 【LeetCode】- Search Insert Position(查找插入的位置)
- [LeetCodeSearch Insert Position
- leetcode Search Insert Position Python
- [LeetCode][Java] Search Insert Position
- leetcode Search Insert Position
- leetcode 35. Search Insert Position
- Leetcode_Search Insert Position
- [LeetCode35]Search Insert Position
- LeetCode---35. Search Insert Position(查找插入位置)
- LeetCode之Search Insert Position
- [leetcode 35] Search Insert Position
- leetcode(35) - Search Insert Position
- LeetCode-35.Search Insert Position
- LeetCode - 35. Search Insert Position
- 【LeetCode】Search Insert Position
- leetcode:Search Insert Position
- [LeetCode] Search in Rotated Sorted Array、Search for a Range、Search Insert Position、Search in Rotate
- LeetCode(35) Search Insert Position
- leetcode — search-insert-position