Image From LeetCodeImage From LeetCode

今天我們要講解的是 [Remove Duplicates From Sorted Array],這在 LeetCode 算是比較簡單的題目,讓我們一起開始吧!

進來之前請先注意,我的方式不一定完全正確,只是依照我自己的理念進行撰寫,所以如果程式上有什麼更好的解法,歡迎提出見解。

這次題目

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

Custom Judge:

The judge will test your solution with the following code:

1
2
3
4
5
6
7
8
9
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

Example

1
2
3
4
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
1
2
3
4
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.

自已解法

這次的題目主要是確認不重複的值有多少個,另外最好能把不重複的值排到最前面,最後他有提供他的測試方法。

解題的思路是,我們要用最簡單的做法去做交換位置,另外他有提到目前已經做過簡單的排序且並非遞減排序,那我們接著只要比較當下的值是否與上一個值不同(也就是非常重複的值),假設是我們就讓他交換位置,接著再把紀錄的錨點k+1,錨點主要是用來辨別目前已經有多少個唯一值。

1
2
3
4
5
6
7
8
9
10
11
12
13
var removeDuplicates = function(nums) {
if (nums.length == 0) return 0;
let k = 0;
for(let j = 1; j < nums.length; j++) {
// 假設不相同,代表我們遇到新的值了
if (nums[k] !== nums[j]) {
// 這邊主要是往上放,也就是說以這個結果為例[0,1,2,3,4,_,_,_,_,_],
// 我們不管排序只管最前面有多少個唯一值就好,所以他後面才是 `_`,因為不管他w
nums[++k] = nums[j];
}
}
return k + 1;
};

實作結果

如此一來就完成了,上方的範例原本的i,我用k來解釋會比較理解一點。

Image From LeetCodeImage From LeetCode