Descriptions: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate ...
Descriptions:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.For example,
Given input array nums =
[1,1,2]
,Your function should return length =
2
, with the first two elements of nums being1
and2
respectively. It doesn't matter what you leave beyond the new length.
我寫的一直有問題...用了HashSet集合,沒有研究過這個類型,[1,1,2]輸出結果一直是[1,1]
(在小本本上記下,要研究HashSet)
import java.util.HashSet;
import java.util.Set;
public class Solution {
public static int removeDuplicates(int[] nums) {
Set<Integer> tempSet = new HashSet<>();
for(int i = 0; i < nums.length; i++) {
Integer wrap = Integer.valueOf(nums[i]);
tempSet.add(wrap);
}
return tempSet.size();
}
}
下麵是優秀答案
Solutions:
public class Solution {
public static int removeDuplicates(int[] nums) {
int j = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != nums[j]) {
nums[++j] = nums[i];
}
}
return ++j;
}
}
有兩個點需要註意:
- 因為重覆的可能有多個,所以不能以相等來做判定條件
- 註意
j++
和++j
的區別,此處用法很巧妙,也很必要!