首页 > 代码库 > Search for a Range
Search for a Range
O(logN)
This question turns to find the first and last element of the target in a sorted array.
Just be careful with the two result coming out of the while loop. The order to add them to the result is different from the frist/last element questions.
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) { // write your code here int[] rst = new int[]{-1, -1}; if (A == null || A.length == 0) { return rst; } //find first element int start = 0; int 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[end] == target) { rst[0] = end; } if (A[start] == target) { rst[0] = start; } //find last 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[start] == target) { rst[1] = start; } if (A[end] == target) { rst[1] = end; } return rst; } }
Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。