簡體   English   中英

在刪除數組中的 K 個連續元素后找到最小幅度

[英]Find the min amplitude after removing K consecutive elements in an array

我試圖在 JavaScript 中找到解決這個問題的方法,時間復雜度為 O(N)。

問題:給定一個由 N 個正整數和一個整數 k 組成的數組 A。 您想從 A 中刪除 k 個連續元素,以使剩余元素的幅度最小。 振幅是最小元素和最大元素之間的差值。

For eg. A[] = [8,7,4,1] and k=2. Output should be 1 because we will remove 4 and 1.

蠻力解決方案很簡單。 可以在 O(n) 中完成嗎? 謝謝

這對你有幫助嗎? 我首先確定 3 個最大的數字(3,因為我們刪除了 2 個連續的數字,這 2 個數字可能是 2 個最大的數字,所以我們需要下一個最大的數字),然后我們對 3 個最小的數字執行相同的操作。

我們創建了一個刪除連續數字的數組,而不改變原始數組。

然后我們只需運行一些 if else 語句來確定 max, min 是否包含在刪除的連續數字中

雖然它不是最漂亮的。 很多 if/else

 const arr = [8, 7, 4, 1] const arr2 = [8, 7, 4, 1, 4, 6, 8] const arr3 = [8, 7, 4, 1, 4, 6, 8, 3, 11, 4, 15] function slice2Consecutive(arr) { let newArr = [] for (let i = 0; i < arr.length - 1; i++) { let s1 = arr[i] let s2 = arr[i + 1] newArr.push([arr[i], arr[i + 1]]) } return newArr } function maxThree(arr) { let one = -Infinity; let two = -Infinity; let three = -Infinity; for (let i = 0; i < arr.length; i += 1) { let num = arr[i]; if (num > three) { if (num >= two) { three = two; if (num >= one) { two = one; one = num; } else { two = num; } } else { three = num; } } } return [one, two, three] } function minThree(arr) { let one = +Infinity; let two = +Infinity; let three = +Infinity; for (let i = 0; i < arr.length; i += 1) { let num = arr[i]; if (num < three) { if (num <= two) { three = two; if (num <= one) { two = one; one = num; } else { two = num; } } else { three = num; } } } return [one, two, three] } function minAmplitude(arr) { const [max, secondMax, thirdMax] = maxThree(arr) const [min, secondMin, thirdMin] = minThree(arr) const slicedArr = slice2Consecutive(arr) const amplitudeArr = [] for (let i = 0; i < slicedArr.length; i++) { let m = max let n = min if (slicedArr[i][0] === max || slicedArr[i][1] === max) { if (slicedArr[i][0] === secondMax || slicedArr[i][1] === secondMax) { m = thirdMax } else { m = secondMax } } if (slicedArr[i][0] === min || slicedArr[i][1] === min) { if (slicedArr[i][0] === secondMin || slicedArr[i][1] === secondMin) { n = thirdMin } else { n = secondMin } } amplitudeArr.push(m - n) } return Math.min(...amplitudeArr) } console.log(minAmplitude(arr)) console.log(minAmplitude(arr2)) console.log(minAmplitude(arr3))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM