問題:
給一數字陣列,陣列內有部分數字重複,把每個不同的數字移動到陣列最前面,回傳有幾個不同的數字。只能在同一個陣列內修改,不能開新陣列。
範例:
1. 輸入:nums = [ 1, 1, 2 ]
輸出: 2, nums = [ 1, 2, _ ] (只會檢查前面不同的數字,那之後的數字都不檢查)
2. 輸入: nums = [ 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 ]
輸出: 5, nums = [ 0, 1, 2, 3, 4, _, _, _, _, _ ]
提問:
沒有,也許可以問一下空陣列的處理
一般想法:
容易被標題中Remove Duplicates誤導,把重複的元素移除。
進階解法:
把不同的元素移到前面即可。
程式:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var removeDuplicates = function (nums) { | |
let j = 1; | |
for (let i = 1; i < nums.length; i++) { | |
if (nums[i] != nums[i - 1]) { | |
nums[j] = nums[i]; | |
j++; | |
} | |
} | |
return j; | |
}; |
文章標籤
全站熱搜