6 回答
TA贡献1827条经验 获得超9个赞
我想从偶数中找到缺失的数字
例如:{2,4,6,8,10,14}; //输出应该是12
我试过:
public class MissingNumber {
public static void main(String[] args) {
int a[] = {2,4,6,8,10,14};
int sum = 0;
for (int i = 0; i<a.length; i++) {
sum = sum + a[i];
}
int sum1 = 0;
for(int j=1; j<=7; j++) {
sum1 = sum1 + j;
}
System.out.println("missing number is:"+(sum1-sum));
}
}
TA贡献1856条经验 获得超17个赞
不确定你为什么要查看总和,除非你确定你的一系列数字总是只缺少一个数字。
否则,这样的事情怎么样:
int a[] = {2,4,6,8,10,14};
int expected = 2;
for (int val : a) {
if (expected != val) {
System.out.println("Missing number is " + expected);
}
expected = expected +2;
}
TA贡献1828条经验 获得超13个赞
我对您的代码进行了一些更改。通过这些改变,你会得到你的答案。
public class MissingNumber {
public static void main(String[] args) {
int a[] = {2,4,6,8,10,14};
int sum = 0;
for (int i = 0; i<a.length; i++) {
sum = sum + a[i];
}
int sum1 = 0;
int even = 2;
for (int j=0; j<=a.length; j++) {
sum1 = sum1 + even;
even = even + 2;
}
System.out.println("missing number is:"+(sum1-sum));
}
}
TA贡献1868条经验 获得超4个赞
上面有很多解决方案,但它们的复杂度都是 O(N)。我相信您可以使用https://en.wikipedia.org/wiki/Binary_search_algorithm用 O(log N) 解决这个问题。
原始代码:
public class MissingNumber {
public static void main(String[] args) {
int a[] = {2,4,8,10, 12, 14};
int start = 0;
int end = a.length;
int pointer = 0;
while (end - start > 1) {
if (a[pointer] == (pointer + 1) * 2) {
start = pointer;
} else {
end = pointer;
}
pointer = (start + end) / 2;
}
System.out.println("Missing element: " + (pointer + 2) * 2);
}
}
您可以添加更多条件。
TA贡献1809条经验 获得超8个赞
您可以尝试对数组元素进行偶数和检查。
public static void main(String[] args) {
int a[] = {2, 4, 6, 8, 10, 14};
int sum = 2;
for (int i = 0; i < a.length; i++) {
if (a[i] != sum) {
System.out.println("missing number is: " + sum);
break;
}
sum = sum + 2;
}
}
TA贡献1865条经验 获得超7个赞
您可以执行以下操作:
// create the set of initial values to use them in filter step.
Set<Integer> givenValues = Arrays.stream(a).boxed().collect(Collectors.toSet());
OptionalInt first =
// generate range by 2 and limit it to size of input array
IntStream.iterate(2, i -> i + 2).limit(a.length)
// filter out only this value that are not in givenValues
.filter(i -> !givenValues.contains(i))
// get first value
.findFirst();
// finally it have to be check if found any value. If not then return default value.
System.out.println("missing number is: "+first.orElse(-1));
它可能过于工程化。但它不依赖于给定输入的顺序。
添加回答
举报