zoukankan      html  css  js  c++  java
  • leetcode 34 在排序数组中查找元素的第一个和最后一个位置

    简介

    暴力, 不过推荐官方的二分查找

    code

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            bool check = false;
            int indexS=-1, indexE = -1;
            for(int i=0; i<nums.size(); i++){
                
                if(nums[i] == target && !check){
                    indexS = i;
                    check = true;
                }else if(check && nums[i] > target){
                    indexE = i - 1;
                    check = false;
                    return {indexS, indexE};
                }
                if(nums[i] > target && !check) return {-1, -1};
            }
            if(check && indexE == -1) {
                indexE = nums.size() - 1;
            }
            return {indexS, indexE};
        }
    };
    
    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int len = nums.length;
            if(len == 0) {
                return new int[]{-1, -1};
            }
    
            int firstPosition = findFirstPosition(nums, target);
            if(firstPosition == -1){
                return new int[] {-1, -1};
            }
    
            int lastPosition = findLastPosition(nums, target);
            return new int[]{firstPosition, lastPosition};
        }
    
        private int findLastPosition(int[] nums, int target) {
            int left = 0;
            int right = nums.length -1;
            while(left < right) {
                int mid = (left + right + 1) >>> 1; // 让其更靠近右边界
                if(nums[mid] < target) {
                    left = mid + 1;
                } else if(nums[mid] == target) {
                    left = mid;
                } else{
                    right = mid - 1;
                }
            }
            return left;
        }
    
        private int findFirstPosition(int[] nums, int target) {
            int left = 0;
            int right = nums.length -1;
            while(left < right) {
                int mid = (left + right) >>> 1;
                if(nums[mid] < target) {
                    left = mid + 1;
                } else if(nums[mid] == target) {
                    right = mid;
                } else{
                    right = mid - 1;
                }
            }
            if(nums[left] == target){
                return left;
            }
            return -1;
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    About learn《The C programming Language,Second Edition》
    Reproduction CVE_2019_0708
    Hello universe!
    WebSessionStore: Could not obtain reference to HttpContext
    oracle 触发器
    IE11,用Forms身份验证保存不了Cookie
    水晶报表
    SAP记账期间变式
    SAP会计年度变式
    SAP OB52会计年度变式
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14844011.html
Copyright © 2011-2022 走看看