My first c++ straightforward solution


  • 1
    X

    After getting lots of help from forum, I posted my first solution as followed.
    My solution is binary search and range search, which is accepted using 9ms.

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int low = 0, high = nums.size() - 1, target_index = 0;
            while(low <= high){
                int mid = (low + high) >> 1;
                if(nums[mid] == target){
                    target_index = mid;
                    break;
                }
                else{
                    if (nums[mid] < target) low = mid + 1;
                    else high = mid - 1;
                }
            }
            
            if (nums[target_index] != target)  //judge if target exist
                return vector<int>{-1,-1};
            
            int target_left = target_index;
            while(target_left - 1 >= 0){
                if (nums[--target_left] == target) continue;
                else{
                    ++target_left;
                    break;
                }
            }
            int target_right = target_index;
            while(target_right + 1 < nums.size()){
                if (nums[++target_right] == target) continue;
                else{
                    --target_right;
                    break;
                }
            }
            return vector<int>{target_left, target_right};
        }
    };
    

  • 1

    It's so great!


  • 0
    X
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.