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.
解题思路:排序然后判断前后连个是否相等;方法二:利用哈希,键是数组的值,value是出现的次数。
java版本1:
package leedcode;
import java.util.Arrays;
public class ContainsDuplicate {
public static boolean isContainsDuplicate(int[] a) {
Arrays.sort(a);
for (int i = 1; i < a.length; i++) {
if (a[i] == a[i - 1])
return true;
}
return false;
}
public static void main(String[] args) {
int[] a = { 1, 3, 4, 5, 6, 55, 7, 2, 8, 2 };
boolean b=isContainsDuplicate(a);
System.out.print(b);
}
}
java版本2, 利用hash:
private static boolean isContainsDuplicate1(int [] a) {
Map<Integer, Integer> m=new HashMap<Integer, Integer>();
for(int num:a){
if(m.containsKey(num))
return true;
m.put(num, 0);
}
return false;
}