• 14 Find First and Last Position of Element in Sorted Array


    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]

    还是用两头逼近的老办法,处理特殊情况的部分有点难看,不过程序运行的结果很不错,就不参考大神做法了。

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            
            vector<int> ans = {-1,-1};
            
            int len = nums.size();
            
            if(len < 1) return ans;
            
            if(len == 1){
                
                if(nums[0] == target)
                {
                    ans[0] = 0;
                    ans[1] = 0;
                    return ans;
                    
                }
                else return ans;
            }
            
        
            int left = 0;
            int right = nums.size() - 1;
            
            if(target < nums[left]) return ans;
            if(target > nums[right]) return ans;
            
            bool l = false;
            bool r = false;
            
            while(left < right)
            {            
                
                if(nums[left]  < target) left++;
                if(nums[right] > target) right--;
                
                
                if(nums[left] == target){
                     ans[0] = left;
                     l = true;
                }
                
                if(nums[right] == target){
                    ans[1] = right;
                    r = true;
                } 
                
                
                if(l&&r) break;
    
            }
            
            
            return ans;
            
        }
    };
    
  • 相关阅读:
    Nightwatch的介绍
    reduce的用法及实例
    什么是声明式渲染?
    H5自带的表单验证
    Flex弹性布局
    JS中的forEach,for in,for of和for的遍历优缺点及区别
    将博客搬至CSDN
    9 外观模式(Facade)
    8 代理模式(Proxy)
    7 装饰模式(Decorator)
  • 原文地址:https://www.cnblogs.com/xiaoyisun06/p/11380424.html
Copyright © 2020-2023  润新知