Leetcode 26 Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only onceand 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 A =[1,1,2],
Your function should return length =2, and A is now[1,2].
1)使用set進行一重篩選後將陣列中元素進行修改
class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int count = 0;
Set<Integer> set = new HashSet<>();
for(int i = 0 ; i < nums.length ; i++){
if(!set.contains(nums[i])){
nums[count++] = nums[i];
set.add(nums[i]);
}
}
return count;
}
}
2)使用雙指標進行標記,比較奇妙(100%)
public class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for(int j = 1; j < nums.length;j++){
if(nums[j] != nums[i]){
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
}
相關文章
- [leetcode]remove-duplicates-from-sorted-array-iiLeetCodeREM
- [LeetCode] 80. Remove Duplicates from Sorted Array IILeetCodeREM
- Remove-duplicates-from-sorted-arrayREM
- 【leetcode】26. Remove Duplicates from Sorted Array 刪除有序陣列的重複元素LeetCodeREM陣列
- LeetCode 83. Remove Duplicates from Sorted ListLeetCodeREM
- Remove-duplicates-from-sorted-listREM
- LeetCode 83.Remove Duplicates from Sorted List(從已排序連結串列中除去重複) Easy/Linked ListLeetCodeREM排序
- Leetcode Remove Duplicates型別題目 (python)LeetCodeREM型別Python
- Leetcode 442. Find All Duplicates in an ArrayLeetCode
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- Leetcode 88. Merge Sorted ArrayLeetCode
- [LeetCode] 3011. Find if Array Can Be SortedLeetCode
- LeetCode 1209. Remove All Adjacent Duplicates in String II 有坑LeetCodeREM
- Leetcode 19 Remove Nth Node From End of ListLeetCodeREM
- [LeetCode] 2487. Remove Nodes From Linked ListLeetCodeREM
- [LeetCode] 702. Search in a Sorted Array of Unknown SizeLeetCode
- LeetCode | 153. Find Minimum in Rotated Sorted ArrayLeetCode
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- LeetCode Remove Nth Node From End of List(019)解法總結LeetCodeREM
- Leetcode(Python3) 19. Remove Nth Node From End of ListLeetCodePythonREM
- # Search in Rotated Sorted Array
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- 88. Merge Sorted Array
- 977. Squares of a Sorted Array
- Array.from()
- Array.from和 Array.of
- 【刷題】Search in a Big Sorted Array
- [leetcode]remove-elementLeetCodeREM
- Find Minimum in Rotated Sorted Array I & II
- javascript Array.from()方法JavaScript
- 資料結構與演算法 | Leetcode 19. Remove Nth Node From End of List資料結構演算法LeetCodeREM
- 108-Convert Sorted Array to Binary Search Tree
- leetcode-27. Remove ElementLeetCodeREM
- Leetcode 27 Remove-ElementLeetCodeREM
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM