问题在于:
给定一个整数数组,查找数组是否包含任何重复项。如果数组中至少出现两次值,则函数应返回true,如果每个元素都不相同,则返回false。
这是我的代码,但是堆栈溢出有错误:
public static class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums.length < 1)
return false;
return recursion(nums, 0, nums.length - 1);
}
private static boolean recursion(int[] nums, int start, int end) {
if ((end - start) == 0) {
return true;
}
if ((end - start) == 1) {
if (nums[start] == nums[end]) {
return false;
} else {
return true;
}
}
boolean first = recursion(nums, start, (end - start) / 2 - 1);
boolean second = recursion(nums, (end - start) / 2, end);
if (first == false || second == false) {
return false;
}
return true;
}
}
答案 0 :(得分:1)
这一行:boolean second = recursion(nums,(end - start)/ 2,end);
尤其如此:(结束 - 开始)/ 2
示例:
start = 0 结束= 3
(3 - 0)/ 2 = 1
(3 - 1)/ 2 = 1
...
开始将始终如一。
第一次递归会出现相同的行为,但start将被阻止为0。
答案 1 :(得分:0)
您可以改为创建HashSet
并检查public boolean containsDuplicate(final int[] nums)
{
Set<Integer> set = new HashSet<Integer>();
for (int i : nums) {
if (set.contains(i)) return true;
set.add(i);
}
return false;
}
答案 2 :(得分:0)
我通过在我身边运行代码来重现您的错误 - 问题是recursion(nums, start, (end - start)/2 - 1)
到达起始索引= 2
且结束索引为-3
的点 - 递归因此永远不会停止。
这是更正 - 我针对这样的数组测试了它:
int[] nums = new int[]{1,2,3,4,5,6,6};
private static boolean recursion(int[] nums, int start, int end) {
if((end - start) == 0){ return false;}
if((end - start) == 1){
//This is really where the recursion should end...unless if there were no duplicate, in which case we repeat
if(nums[start] == nums[end]){
return true;
}
else{
//we checked all against the first number - now we move the start to the next item on list
//so our new START is (start+1) and our new END (length-1)
return recursion(nums, (start+1), (nums.length-1));
}
}
else{
if(end < 0){return false;}
//here you evaluate if the start and end numbers are different
if(nums[start] == nums[end]){return true;}
return recursion(nums, start, (end - 1));
}
}
请用上面的代码替换你的“递归”功能,让我们看看它是否适合你。
答案 3 :(得分:0)
BruteForce方法:
步骤:
- 您可以采取外循环遍历nums数组直到length-1。
- 内循环可以从i + 1开始直到nums.length
- 在每次迭代中,我们可以比较两个值 nums [i]和nums [j]
- 如果两个值都相等,那么我们可以返回true,否则返回false
- 因为它是蛮力方法,所以需要O(n ^ 2)的时间复杂度。
class Solution {
public boolean containsDuplicate(int[] nums) {
for(int i = 0; i<nums.length-1; i++){
for(int j = i+1; j<nums.length; j++){
if(nums[i] == nums[j]){
return true;
}
}
}
return false;
}
}