Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
题目理解:输入字符串(引用),可另外使用O(1)空间更改此字符串使没有重复字符。
由于在同一字符串上操作,修改后的字符串可理解为前k(=newStr.len)位为有效位的字符串,修改前后调用字符串的引用不变,因此返回k便可知修改后的字符串。
Solutions:
Java:
save the index of the number to be compared
compare in the loop and change the number in location 'l' when it differs from nums[save]
class Solution {
public int removeDuplicates(int[] nums) {
int l = 1; // locate the index of the place to be changed and count the effective digits
if (nums == null)
return -1;
int save = 0; //index of the current saved number
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[save]) {
nums[l++] = nums[i];
save = i;
}
}
return l;
}
}
set the location to be saved in to i
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i == 0 || n > nums[i-1])
nums[i++] = n;
return i;
}
public int removeDuplicates(int[] nums) {
int i = nums.length > 0 ? 1 : 0;
for (int n : nums)
if (n > nums[i-1])
nums[i++] = n;
return i;
}
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/11780/5-lines-C%2B%2BJava-nicer-loops
C:
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n < 2) return n;
int id = 1;
for(int i = 1; i < n; ++i)
if(A[i] != A[i-1]) A[id++] = A[i];
return id;
}
};
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/11757/My-Solution-%3A-Time-O(n)-Space-O(1)
C++:
count the number that has appeared (saved in count)
the correct place for the first appear number is i-count
int count = 0;
for(int i = 1; i < n; i++){
if(A[i] == A[i-1]) count++;
else A[i-count] = A[i];
}
return n-count;
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/11782/Share-my-clean-C%2B%2B-code
set the location to be saved in to i
int removeDuplicates(vector<int>& nums) {
int i = 0;
for (int n : nums)
if (!i || n > nums[i-1])
nums[i++] = n;
return i;
}
int removeDuplicates(vector<int>& nums) {
int i = !nums.empty();
for (int n : nums)
if (n > nums[i-1])
nums[i++] = n;
return i;
}
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/11780/5-lines-C%2B%2BJava-nicer-loops