1. 程式人生 > >Find First and Last Position of Element in Sorted Array(數組中查找第一個元素和最後一個元素)

Find First and Last Position of Element in Sorted Array(數組中查找第一個元素和最後一個元素)

run nbsp arc example col ascend == sea 如果

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

思路:題目要求時間復雜度為O(log n),且數組有序,可用二分查找法。但數組中有重復的元素,因此需要對二分查找作一點修改。

代碼

    //二分查找 -- 有重復元素  查找最開頭與最結尾的目標值
    public static int[] searchRange(int[] nums, int target) {
        
        int[] res = new int[2];
        List<Integer> l = new
ArrayList<>(); int left = 0; int right = nums.length-1; while(left<=right){ int mid = (left+right)/2; if(nums[mid]==target){ int start = mid; int end = mid; //獲取start的索引
while(start>=0){ if(nums[start]!=target){ break; } start--; } l.add(start+1); //獲取end的索引 while(end<=nums.length-1){ if(nums[end]!=target){ break; } end++; } l.add(end-1); break; }else if(nums[mid]<target){ left = mid+1; }else{ right = mid-1; } } if(l.size()==0){ res[0] = -1; res[1] = -1; }else{ res[0] = l.get(0); res[1] = l.get(1); } return res; }

當然,如果不考慮時間復雜度,也可用暴力法。

代碼:

    //暴力循環
     public static int[] searchRange(int[] nums, int target) {
        
        int[] res = new int[2];
        List l = new ArrayList<>();
         
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == target){
                l.add(i);
            }
        }
        
        if(l.size()==0){
           res[0] = res[1] =-1;
        }else if(l.size()==1){
            res[0] = res[1] = (int) l.get(0);
        }else{
            res[0] = (int) l.get(0);
            res[1] = (int) l.get(l.size()-1);
        }
        
         return res;
     }

Find First and Last Position of Element in Sorted Array(數組中查找第一個元素和最後一個元素)