• 刷题581. Shortest Unsorted Continuous Subarray


    一、题目说明

    题目581. Shortest Unsorted Continuous Subarray,求最大连续子数组(如果该子数组有序,则整个数组有序)的长度。难度是Easy!

    二、我的解答

    不动脑子,将数组排序,然后从左到右比较,再从右到左比较。即可获得最短子数组的长度。

    class Solution{
    	public:
    		int findUnsortedSubarray(vector<int>& nums){
    			int len = nums.size()-1;
    			vector<int> tmp;
    			for(int i=0;i<nums.size();i++){
    				tmp.push_back(nums[i]);
    			}
    			sort(tmp.begin(),tmp.end());
    			int left = 0,right = len;
    			while(left<len && tmp[left]==nums[left]){
    				left++;
    			}
    			while(right>=left && tmp[right]==nums[right]){
    				right--;
    			}
    			return (right-left+1);
    		}
    };
    

    性能如下:

    Runtime: 44 ms, faster than 51.61% of C++ online submissions for Shortest Unsorted Continuous Subarray.
    Memory Usage: 11.3 MB, less than 38.10% of C++ online submissions for Shortest Unsorted Continuous Subarray.
    

    三、优化措施

    优化如下:

    class Solution{
    	public:
    		int findUnsortedSubarray(vector<int>& nums){
    			int m = nums[0], n = nums.back(), l = -1, r = -2;
    	        int len = nums.size();
    	        //从左到右遍历,如果nums[i]比前面的都大,则i+1的位置正确 
    	        for (int i = 1; i < len; ++i)
    	        {
    	            m = max(m, nums[i]);
    	            n = min(n, nums[len - 1 - i]);
    	            if (m != nums[i]) r = i;
    	            if (n != nums[len - 1 - i]) l = len - 1 - i;
    	        }
    	        return r - l + 1;
    		}
    };
    

    性能如下:

    Runtime: 36 ms, faster than 77.82% of C++ online submissions for Shortest Unsorted Continuous Subarray.
    Memory Usage: 10.5 MB, less than 71.43% of C++ online submissions for Shortest Unsorted Continuous Subarray.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    NFS原理
    linux NFS配置案例
    centos swap分区
    git常用命令
    MHA介绍和基础、原理、架构、工具介绍
    mysql5.7.26部署MHA
    mysql5.7.26 基于GTID的主从复制环境搭建
    MHA监控进程异常退出(MHA版本:0.56)
    mysql 主从 Last_IO_Errno错误代码说明
    mysql 在gtid环境下缺少一部分binlog部署从库
  • 原文地址:https://www.cnblogs.com/siweihz/p/12313073.html
Copyright © 2020-2023  润新知