LeetCode - Algorithms - 217. Contains Duplicate

Tag easy as it is. This problem is like 387. First Unique Character in a String.

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public boolean containsDuplicate(int[] nums) {
boolean r = false;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
if (map.containsKey(nums[i])) {
int val = map.get(nums[i]);
map.put(nums[i], val+1);
}
else {
map.put(nums[i], 1);
}
}
Iterator<Integer> itr = map.values().iterator();
while(itr.hasNext()) {
if (itr.next().intValue()>1) {
r = true;
break;
}
}
return r;
}
}

Submission Detail

  • 18 / 18 test cases passed.
  • Runtime: 13 ms
  • Your runtime beats 48.76 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
var r = false;
var count = {};
for(var i=0;i<nums.length;i++) {
if (typeof count[nums[i]]!="undefined" && count[nums[i]]!=null) {
count[nums[i]]++;
}
else {
count[nums[i]]=1;
}
}
for(var i in count) {
if (count[i]>1) {
r = true;
break;
}
}
return r;
};

Submission Detail

  • 18 / 18 test cases passed.
  • Runtime: 92 ms
  • Your runtime beats 35.80 % of javascript submissions.