您的位置:首页 > 大数据 > 人工智能

Contains Duplicate

2015-06-16 07:52 453 查看
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.

判断数组中是否有重复数字出现;

代码一:(不做任何处理,超时)

package leetcode;

public class ContainsDuplicate1 {

public boolean containsDuplicate(int[]
nums) {
boolean ans =
false;
if (nums.length <=0)
return ans;
for (int
i = 0; i<nums.length;
i++){
if (i <
nums.length-1){
for (int
j = i+1; j<nums.length;
j++){
if (nums[i] ==
nums[j]) return
true;
}
}
}
return ans;
}

public static
void main(String[] args) {
//
TODO Auto-generated method stub
int[]
nums = {0,31,23,42,25,4645,567,657,34,31};
System.out.println(new ContainsDuplicate1().containsDuplicate(nums));
}

}
代码二:(使用快排,然后在判断相邻两个数字是否相等,超时)

public static
void quickSort(int[] array){
if(array !=
null){
quickSort(array, 0,
array.length-1);
}
}

private static
void quickSort(int[] array,int
beg,int end){
if(beg >=
end || array == null)
return;
int p = partition(array,
beg, end);
quickSort(array, beg,
p-1);
quickSort(array, p+1,
end);
}

private static
int partition(int n[],
int left, int
right) {
int pivot =
n[left];
while (left <
right) {
while (left <
right && n[right] >=
pivot)
right--;
if (left <
right)
n[left++] =
n[right];
while (left <
right && n[left] <=
pivot)
left++;
if (left <
right)
n[right--] =
n[left];
}
n[left] =
pivot;
return left;
}

public boolean containsDuplicate(int[]
nums) {
boolean
ans = false;
quickSort(nums);
int
len = nums.length;
for (int
i = 1; i<len;
i++){
if (nums[i-1] ==
nums[i]) return
true;
}
return
ans;
}

解法三:使用HashSet,AC

public boolean containsDuplicate(int[]
nums) {
boolean
ans = false;
HashSet<Integer> appearedNum =
new HashSet<Integer>();
int
len = nums.length;
for (int
i = 0; i<len;
i++){
if (appearedNum.contains(nums[i]))
return true;
else
appearedNum.add(nums[i]);
}
return
ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: