leetcode 34. Search for a Range
2016-08-10 23:45
253 查看
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return
Example
Given
target value
return
分析:
这道题我们只需要分别对起点和终点用二分法就可以啦~
If the target is not found in the array, return
[-1, -1].
Example
Given
[5, 7, 7, 8, 8, 10]and
target value
8,
return
[3, 4].
分析:
这道题我们只需要分别对起点和终点用二分法就可以啦~
public class Solution { /** *@param A : an integer sorted array *@param target : an integer to be inserted *return : a list of length 2, [index1, index2] */ public int[] searchRange(int[] A, int target) { if (A.length == 0) { return new int[]{-1, -1}; } int[] result = new int[2]; int start, end; //search the first element start = 0; end = A.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (A[mid] == target) { end = mid; } else if (A[mid] < target) { start = mid; } else { end = mid; } } if(A[start] == target) { result[0] = start; } else if (A[end] == target){ result[0] = end; } else { result[0] = result[1] = -1; return result; } //search the second element start = 0; end = A.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (A[mid] == target) { start = mid; } else if (A[mid] < target) { start = mid; } else { end = mid; } } if(A[end] == target) { result[1] = end; } else if (A[start] == target){ result[1] = start; } else { result[0] = result[1] = -1; return result; } return result; } }
相关文章推荐
- LeetCode 34.Search for a Range
- [leetcode 34] Search for a Range
- LeetCode_34---Search for a Range
- [Leetcode 34, Medium] Search for a Range
- leetcode 34: Search for a Range
- LeetCode 34 Search for a Range
- Search for a Range - LeetCode 34
- LeetCode 34: Search for a Range
- [Leetcode] 34. Search for a Range
- 【LeetCode】34. Search for a Range
- Leetcode_34_Search for a Range
- [leetcode 34] Search for a Range
- leetcode 34 -- Search for a Range
- LeetCode --- 34. Search for a Range
- [LeetCode]34 Search for a Range
- LeetCode 34 — Search for a Range(C++ Java Python)
- LeetCode 34 Search For A Range 二叉查找相关(二)
- 【LeetCode 34】Search for a Range
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- leetcode_34——Search for a Range(二分查找)