Given an unsorted array of integers, remove all duplicate elements so that each element appears only once, preserving the order of their first occurrence.
Input: [1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]Output: [1,5,2,6,8,9,10,3,4,11]Explanation: All duplicates are removed, and the order of first appearance is preserved.
classSolution {
public: vector<int> removeDuplicates(vector<int>& arr) {
vector<int> ans;
for (int x : arr) {
bool found = false;
for (int y : ans) if (x == y) { found = true; break; }
if (!found) ans.push_back(x);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funcremoveDuplicates(arr []int) []int {
ans:= []int{}
for_, x:=rangearr {
found:=falsefor_, y:=rangeans {
ifx==y {
found = truebreak }
}
if !found {
ans = append(ans, x)
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
classSolution {
public List<Integer>removeDuplicates(int[] arr) {
List<Integer> ans =new ArrayList<>();
for (int x : arr) {
boolean found =false;
for (int y : ans) if (x == y) { found =true; break; }
if (!found) ans.add(x);
}
return ans;
}
}
1
2
3
4
5
6
7
8
from typing import List
classSolution:
defremoveDuplicates(self, arr: list[int]) -> list[int]:
ans: list[int] = []
for x in arr:
if x notin ans:
ans.append(x)
return ans
import java.util.*;
classSolution {
public List<Integer>removeDuplicates(int[] arr) {
Set<Integer> seen =new HashSet<>();
List<Integer> ans =new ArrayList<>();
for (int x : arr) {
if (!seen.contains(x)) {
ans.add(x);
seen.add(x);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
from typing import List
classSolution:
defremoveDuplicates(self, arr: list[int]) -> list[int]:
seen: set[int] = set()
ans: list[int] = []
for x in arr:
if x notin seen:
ans.append(x)
seen.add(x)
return ans
import java.util.*;
classSolution {
public List<Integer>removeDuplicates(int[] arr) {
Arrays.sort(arr);
List<Integer> ans =new ArrayList<>();
for (int i = 0; i < arr.length; ++i) {
if (i == 0 || arr[i]!= arr[i-1]) ans.add(arr[i]);
}
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution:
defremoveDuplicates(self, arr: list[int]) -> list[int]:
arr.sort()
ans: list[int] = []
for i, x in enumerate(arr):
if i ==0or x != arr[i-1]:
ans.append(x)
return ans