如何解决我的“仅重复计数”代码不起作用编写了易于理解的干净代码根据我的说法
这是我的代码:
public static Point findRepeating(Integer arr[],int n)
{
// Point(return type) is a class having first and second as data memebres where first is number
// repeating and second is number of times it is repeating
if(arr[0] == arr[n-1]) // whole array has only one number
return new Point(arr[0],n);
int low = 0,high = n-1,mid = (low+high)/2,repNumber = 0;
while(high-low > 1) // in this loop only I'm trying to find the number that is repeating
{
mid = (low+high)/2;
if(arr[mid] == arr[mid-1] || arr[mid] == arr[mid+1])
{
repNumber = arr[mid];
break;
}
if((arr[low]+(mid-low)) == arr[mid])
low = mid+1;
else
high = mid;
}
int startIndex=0,endIndex=0;
// now I'll find the start and end index of the repeating number
// doing this by finding number just smaller and just larger than repeating number
if(repNumber == arr[0])
{
startIndex = 0;
endIndex = Arrays.binarySearch(arr,repNumber+1);
return new Point(repNumber,endIndex);
}
if(repNumber == arr[n-1])
{
endIndex = n-1;
startIndex = Arrays.binarySearch(arr,repNumber-1);
return new Point(repNumber,endIndex-startIndex);
}
else
{
startIndex = Arrays.binarySearch(arr,repNumber-1) + 1;
endIndex = Arrays.binarySearch(arr,endIndex-startIndex);
}
}
我的代码失败的测试用例是(整个输入不可见,因为它很大):
错误的答案。 !!!错误答案
可能您的代码无法针对多个测试用例 (TC) 正常工作。
您的代码失败的第一个测试用例:
输入: 28566 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 3 4 3 4 3 4 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 5 3 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 15.................
它的正确输出是: 16932 10086
您的代码的输出是: 0 0
解决方法
在时间复杂度小于 O(N) 的情况下使用线性搜索可以简单地解决这个问题(最坏情况下为 O(N))。 第一步,我们可以检查数组的第一个和最后一个元素是否相等?
如果是, 我们可以返回数组的大小作为我们的答案。 否则我们可以使用两种方法进行线性检查
方法一:我们可以取两个数字之间的连续差值,并检查它们是否给我们零作为结果
int count = 0;
vector<int>arr = { 1,2,3 };
for(int i = 0; i < arr.size() ; i++){
if(arr[i+1] - arr[i] == 0 ){
count++;
}
}
方法二:通过对数组的两个连续元素进行异或,当异或为零时增加计数
int count = 0;
vector<int>arr = { 1,3 };
for(int i = 0; i < arr.size() ; i++){
if((arr[i+1]^arr[i]) == 0 ){
count++;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。