zoukankan      html  css  js  c++  java
  • 20.12.1 leetcode34

    题目链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

    题意:给你一个有序数组和一个target值,让求target值出现的第一次位置和最后一次位置。

    分析:二分很明显,不过我自己的方法只是二分查找target值,随便找到一个target值之后遍历周围获得位置,而题解方法要巧妙很多:

    找leftIdx即为在数组中寻找第一个大于等于target的下标,寻找rightIdx即为在数组中寻找第一个大于target的下标,然后将下标减一。

    先是我的菜鸡代码

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int n=nums.size();
            vector<int> ans(2);
            ans[0]=-1,ans[1]=-1;
            int l=0,r=n-1;
            while(l<=r){
                int mid=(l+r)/2;
                //cout<<l<<" "<<r<<" "<<mid<<endl;
                if(nums[mid]<target){
                    l=mid+1;
                }else if(nums[mid]>target){
                    r=mid-1;
                }else if(nums[mid]==target){
                    ans[0]=mid,ans[1]=mid;
                    while((ans[0]-1)>=0&&nums[ans[0]-1]==nums[mid])ans[0]-=1;
                    while((ans[1]+1)<n&&nums[ans[1]+1]==nums[mid])ans[1]+=1;
                    break;
                }
            }
            return ans;
        }
    };

    题解的:

    class Solution { 
    public:
        int binarySearch(vector<int>& nums, int target, bool lower) {
            int left = 0, right = (int)nums.size() - 1, ans = (int)nums.size();
            while (left <= right) {
                int mid = (left + right) / 2;
                if (nums[mid] > target || (lower && nums[mid] >= target)) {
                    right = mid - 1;
                    ans = mid;
                } else {
                    left = mid + 1;
                }
            }
            return ans;
        }
    
        vector<int> searchRange(vector<int>& nums, int target) {
            int leftIdx = binarySearch(nums, target, true);
            int rightIdx = binarySearch(nums, target, false) - 1;
            if (leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target) {
                return vector<int>{leftIdx, rightIdx};
            } 
            return vector<int>{-1, -1};
        }
    };
  • 相关阅读:
    Cisco Packet Tracer 7.2
    "%Error opening tftp://255.255.255.255/network config"
    CPI 3.0磁盘空间不足!
    ASA Failover
    思科交换机配置单播MAC地址过滤
    WLC HA模式下的注意事项
    802.11r mixed mode
    IEEE 802.11r-2008
    iOS 上通过 802.11k、802.11r 和 802.11v 实现 Wi-Fi 网络漫游
    Flexconnect部署
  • 原文地址:https://www.cnblogs.com/qingjiuling/p/14070660.html
Copyright © 2011-2022 走看看