LeetCode & Q26-Remove Duplicates from Sorted Array-Easy
程序员文章站
2022-04-01 11:51:48
...
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
的区别,此处用法很巧妙,也很必要!
以上就是LeetCode & Q26-Remove Duplicates from Sorted Array-Easy的详细内容,更多请关注其它相关文章!
推荐阅读
-
【一天一道LeetCode】#26. Remove Duplicates from Sorted Array
-
LeetCode 83. Remove Duplicates from Sorted List
-
LeetCode 83. Remove Duplicates from Sorted List
-
LeetCode 83. Remove Duplicates from Sorted List ***
-
Leetcode 83. Remove Duplicates from Sorted List
-
Leetcode No.26 Remove Duplicates from Sorted Array(c++实现)
-
【LeetCode】80. Remove Duplicates from Sorted Array II (删除排序数组中的重复项 II)-C++实现及详细图解
-
【LeetCode】26. Remove Duplicates from Sorted Array (删除排序数组中的重复项)-C++实现的两种方法
-
leetcode26:Remove Duplicates from Sorted Array
-
【一天一道LeetCode】#26. Remove Duplicates from Sorted Array