赞
踩
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。要求时间复杂度为O(log n),若数组中不存在目标值,返回[-1,1]。
class Solution { public int[] searchRange(int[] nums, int target) { int[] res=new int[2]; res[0]=serachStart(nums, target); res[1]=serachEnd(nums, target); return res; } public int serachStart(int[] nums, int target){ int start=search(nums, target, 0, nums.length-1); if(start==-1) return -1; int temp=-1; while(true){ temp=search(nums, target, 0, start-1); if(temp==-1) break; else start=temp; } return start; } public int serachEnd(int[] nums, int target){ int end=search(nums, target, 0, nums.length-1); if(end==-1) return -1; int temp=-1; while(true){ temp=search(nums, target, end+1, nums.length-1); if(temp==-1) break; else end=temp; } return end; } public int search(int[] nums, int target, int low, int high){ int mid=-1; while(low<=high){ mid=low+(high-low)/2; if(nums[mid]==target) return mid; else if(nums[mid]<target) low=mid+1; else high=mid-1; } return -1; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。