Contains Duplicate 解答

Question

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Solution 1 HashMap

Time complexity O(n), space cost O(n)

 public class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
int length = nums.length;
if (length <= 1)
return false;
for (int i = 0; i < length; i++) {
if (counts.containsKey(nums[i]))
return true;
else
counts.put(nums[i], 1);
}
return false;
}
}

Solution 2 Set

Time complexity O(n), space cost O(n)

 public class Solution {
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if (length <= 1)
return false;
Set<Integer> set = new HashSet<Integer>();
for (int i : nums) {
if (!set.add(i))
return true;
}
return false;
}
}
上一篇:[Head First Python]4.读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out


下一篇:Linux通过端口转发来访问内网服务(端口转发访问阿里云Redis数据库等服务)