6 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
我想從偶數(shù)中找到缺失的數(shù)字
例如:{2,4,6,8,10,14}; //輸出應(yīng)該是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貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
不確定你為什么要查看總和,除非你確定你的一系列數(shù)字總是只缺少一個(gè)數(shù)字。
否則,這樣的事情怎么樣:
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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
我對(duì)您的代碼進(jìn)行了一些更改。通過這些改變,你會(huì)得到你的答案。
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貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
上面有很多解決方案,但它們的復(fù)雜度都是 O(N)。我相信您可以使用https://en.wikipedia.org/wiki/Binary_search_algorithm用 O(log N) 解決這個(gè)問題。
原始代碼:
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貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以嘗試對(duì)數(shù)組元素進(jìn)行偶數(shù)和檢查。
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貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以執(zhí)行以下操作:
// 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));
它可能過于工程化。但它不依賴于給定輸入的順序。
添加回答
舉報(bào)