首页 > 代码库 > LeetCode Search for a Range
LeetCode Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm‘s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
二分法查找,虽然AC了,但写的不太好。
public class Solution { ArrayList<Integer> arrayList=new ArrayList<>(); int[] res=new int[]{-1,-1}; public int[] searchRange(int[] A, int target) { if (A.length==0) { return null; } int middle = (A.length-1)/2; int end=A.length-1; if (A[middle]>target) { search(A, 0, middle, target); }else if (A[middle]<target) { search(A, middle, end, target); } else { search(A, 0, middle, target); search(A, middle+1, end, target); } if (arrayList.isEmpty()) { return res; }else { res[0]=arrayList.get(0); res[1]=arrayList.get(arrayList.size()-1); return res; } } private void search(int[] A,int begin,int end,int target) { if(begin>end){ return; } if (begin==end) { if (A[begin]==target) { if (!arrayList.contains(begin)) { arrayList.add(begin); } } return; } int middle = (begin+end)/2; if (A[middle]>target) { search(A, begin, middle, target); return; } if (A[middle]<target) { search(A, middle+1, end, target); return; } if (A[middle]==target) { search(A, begin, middle, target); search(A, middle+1, end, target); return; } }}
LeetCode Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。