摘要:如果數(shù)組是亂序的,我們就要找出這個(gè)數(shù)組的最小子數(shù)組,以滿足,只要排序好這個(gè)子數(shù)字,整個(gè)數(shù)字就是有序的。我們用一個(gè)變量來(lái)保存遍歷過(guò)的元素中的最大值,用一個(gè)變量來(lái)保存從數(shù)組尾部遍歷的元素中的最小值。
題目詳情
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.思路
You need to find the shortest such subarray and output its length.題目的意思是輸入一個(gè)數(shù)組,這個(gè)數(shù)組可能是排序好的,也可能是亂序的。如果數(shù)組是亂序的,我們就要找出這個(gè)數(shù)組的最小子數(shù)組,以滿足,只要排序好這個(gè)子數(shù)字,整個(gè)數(shù)字就是有序的。
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: 只需要排序[6,4,8,10,9]就可以保證整個(gè)數(shù)組的有序
大體思路是這樣的:如果當(dāng)前元素比它前面的元素中的最大的值小,那它就在待排序的子數(shù)組里;如果當(dāng)前元素比它后面元素中的最小值要大,那它也需要包含在待排序的子數(shù)組里。
我們用一個(gè)變量(max)來(lái)保存遍歷過(guò)的元素中的最大值,用一個(gè)變量(min)來(lái)保存從數(shù)組尾部遍歷的元素中的最小值。
然后我們只要通過(guò)遍歷找到,最后一位待排序元素和最前面的待排序元素就可以了。
解法public int findUnsortedSubarray(int[] nums) { int length = nums.length; int start =-1 ; int end = -2; int min = nums[length-1]; int max = nums[0]; for(int i=1;imin){ start = length-1-i; } } return end-start+1; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/68397.html
摘要:前言從開(kāi)始寫(xiě)相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒(méi)有按順序?qū)懍F(xiàn)在翻起來(lái)覺(jué)得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開(kāi)始寫(xiě)leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒(méi)有按順序?qū)憽F(xiàn)在翻起來(lái)覺(jué)得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。 順序整理 1~50 1...
摘要:在線網(wǎng)站地址我的微信公眾號(hào)完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語(yǔ)言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號(hào): showImg(htt...
摘要:較早放入的元素在隊(duì)列頂部最近放入的元素在隊(duì)列尾部檢查最近放入的,保證隊(duì)列中新放入的及對(duì)應(yīng)的均為遞增反證若保留,那么在下面第二個(gè)循環(huán),該元素有可能中斷循環(huán),并使得我們無(wú)法得到隊(duì)列更左邊的最優(yōu)解檢查較早放入的最小距離 Problem Return the length of the shortest, non-empty, contiguous subarray of A with sum...
Problem Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sum...
Problem Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note:The length o...
閱讀 1057·2021-11-15 18:11
閱讀 3177·2021-09-22 15:33
閱讀 3473·2021-09-01 11:42
閱讀 2671·2021-08-24 10:03
閱讀 3632·2021-07-29 13:50
閱讀 2939·2019-08-30 14:08
閱讀 1286·2019-08-28 17:56
閱讀 2268·2019-08-26 13:57