1. 程式人生 > >【LeetCode】【找元素】Find First and Last Position of Element in Sorted Array

【LeetCode】【找元素】Find First and Last Position of Element in Sorted Array

com pub bsp starting tin example pan ray 範圍

描述:

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]

思路一:一次Binary Search

先使用二分查找找到和taget相等的起始位置的元素,然後在這個位置向兩邊擴散找到值相同的範圍。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res(2,-1);
        if(nums.size() == 0
) return res; int cau = dichotomy(nums,target); if(cau == -1) return res; else{ int i = cau,j = cau; cout<<cau<<endl; while((i>=0 && nums[i] == target) || (j<=nums.size()-1 && nums[j] == target)){
if(i>=0 && nums[i] == target){ res[0] = i; cout<<i<<endl; i--; } if(j<=nums.size()-1 && nums[j] == target){ res[1] = j; cout<<j<<endl; j++; } } } return res; } int dichotomy(vector<int>& nums, int target){ int low = 0,int high = nums.size() - 1; while(low < high){ int mid = (low + high + 1) / 2; if(nums[mid] == target) return mid; if(nums[mid] < target) low = mid + 1; else high = mid - 1; } return -1; } };

思路二:兩3次Binary Search

先根據上述的二分查找,找到起始位置的元素,然後從low開始繼續使用一次二分查找找到target+1的位置,然後返回這個位置it - 1,從而找到起始和終止的範圍。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res(2,-1);
        if(nums.size() == 0) return res;
        int low = dichotomy(nums,target,0);   //找起始元素
        cout<<low<<endl;
        if(low == nums.size() || nums[low] != target)  //可能出現到數組結尾還是target比low處元素大,low=nums.size
            return res;
        else{
            res[0] = low;
            res[1] = dichotomy(nums,target+1,low) - 1;   //找結尾元素
        }
        return res;
    }
    
    int dichotomy(vector<int>& nums, int target, int low){
        int high = nums.size(); //核心  
        while(low < high){
            int mid = (low + high ) / 2;  
            if(nums[mid] < target) low = mid + 1;
            else high = mid;
        }
        return low;
    }
};

【LeetCode】【找元素】Find First and Last Position of Element in Sorted Array