classSolution { public: boolcontainsDuplicate(vector<int>& nums){ sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { returntrue; } } returnfalse; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publicbooleancontainsDuplicate(int[] nums) { Arrays.sort(nums); intn= nums.length; for (inti=0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { returntrue; } } returnfalse; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9
funccontainsDuplicate(nums []int)bool { sort.Ints(nums) for i := 1; i < len(nums); i++ { if nums[i] == nums[i-1] { returntrue } } returnfalse }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
intcmp(constvoid* _a, constvoid* _b) { int a = *(int*)_a, b = *(int*)_b; return a - b; }
boolcontainsDuplicate(int* nums, int numsSize) { qsort(nums, numsSize, sizeof(int), cmp); for (int i = 0; i < numsSize - 1; i++) { if (nums[i] == nums[i + 1]) { returntrue; } } returnfalse; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10
var containsDuplicate = function(nums) { nums.sort((a, b) => a - b); const n = nums.length; for (let i = 0; i < n - 1; i++) { if (nums[i] === nums[i + 1]) { returntrue; } } returnfalse; };
classSolution { publicbooleancontainsDuplicate(int[] nums) { Set<Integer> set = newHashSet<Integer>(); for (int x : nums) { if (!set.add(x)) { returntrue; } } returnfalse; } }
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10
funccontainsDuplicate(nums []int)bool { set := map[int]struct{}{} for _, v := range nums { if _, has := set[v]; has { returntrue } set[v] = struct{}{} } returnfalse }