$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Self-defined math definitions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Math symbol commands \newcommand{\intd}{\,{\rm d}} % Symbol 'd' used in integration, such as 'dx' \newcommand{\diff}{{\rm d}} % Symbol 'd' used in differentiation ... $$

34. 在排序数组中查找元素的第一个和最后一个位置

题目描述查看:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

  题目的意思是从一个有序的数组中,查找一个数,但是这个数是重复存在的,返回区间。题目要求的时间复杂度O(logn),提醒我们用到二分查找。

  • 思路

先用二分查找找到这个数,在创建新指针找数的左右边界。

当找到这个数的时候,设定l,r指针先指向这个数,然后左右扩展找边界。

 1 if(nums[mid] == target) {
 2     int l = mid;
 3     int r = mid;
 4     int i = 0;
 5     while(l >= left && r <= right){
 6         i++;
 7         if((mid-i >=0 && nums[mid -i] ==target) ||( mid + i < nums.length && nums[mid + i] == target)) {
 8             if (mid-i >=0 && nums[mid -i] ==target) l--;
 9             if (mid + i < nums.length && nums[mid + i] == target) r++;
10         } else {
11             result[0] = l;
12             result[1] = r;
13             return result;
14         }
15     }
16 }
  • 边界条件

7行要判断数组下标是否越界,然后以mid为中心,以i为左右移动的长度,进行判定。

 1     public static int[] search(int[] nums, int target) {
 2         int[] result = {-1,-1};
 3         if(nums.length == 0)return result;
 4         int left = 0;
 5         int right = nums.length - 1;
 6         while(left <= right){
 7             int mid = left +(right - left)/2;
 8             if(nums[mid] == target) {
 9                 int l = mid;
10                 int r = mid;
11                 int i = 0;
12                 while(l >= left && r <= right){
13                     i++;
14                     if((mid-i >=0 && nums[mid -i] ==target) ||( mid + i < nums.length && nums[mid + i] == target)) {
15                         if (mid-i >=0 && nums[mid -i] ==target) l--;
16                         if (mid + i < nums.length && nums[mid + i] == target) r++;
17                     } else {
18                         result[0] = l;
19                         result[1] = r;
20                         return result;
21                     }
22                 }
23             }
24             else if(nums[mid] > target)right = mid -1;
25             else
26                 left = mid +1;
27             }
28         return result;
29     }

 

posted @ 2020-03-28 21:17  V丶vvv  阅读(442)  评论(0编辑  收藏  举报