我想将数组的每个元素与其他元素进行比较。如果两个元素相等,那么一个应该更改为1,另一个元素应该更改为0.
我做错了什么?
package org.kodejava.example.io;
import java.util.Arrays;
public class Root {
public static void main(String[] args) {
System.out.println(Arrays.toString(arr()));
}
public static int[] arr() {
int[] arc ={1,2,5,76,8,0,6,5,1,4,8,4,6,};
for (int i=0;i<13;i++){
for (int j=1;j<13;j++){
if (arc[i] == arc[j] ) {
arc[i]=1;
arc[j]=0;
}
else {
arc[i]=1;
}
}
}
return arc;
}
}
在这个例子中,我希望得到一个类似的行:[1, 1, 1, 1, 1, 1, 1, 0, 0, 1...]
然而,我的尝试以[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
提前致谢!
另一个例子,如果我们有一个序列[1,1,4,6]
,那么最终结果应该是[1,0,1,1]
。因此,如果元素被多次满足,则只有一个元素必须等于1而其他元素必须等于0。
答案 0 :(得分:5)
也许这就是你想要的功能:
public static int[] arr() {
int[] arc ={1,2,5,76,8,0,6,5,1,4,8,4,6};
for (int i=0;i<arc.length;i++){
for (int j=i+1;j<arc.length;j++){
if (arc[i] == arc[j] && arc[i] != 0) {
arc[i]=1;
arc[j]=0;
}
}
if(arc[i] != 0) {
arc[i] = 1;
}
}
return arc;
}
注意arc.length
和arc[i] != 0
检查,内部循环来自i+1
。
<强>更新强>
我重写了我的函数,以便它现在满足条件,即最后0应该是1。它现在将数组作为参数。有一些优化,因为如果相应索引上的元素已经为0,则内循环将不会运行。
import java.util.Arrays;
public class Root {
public static void main(String[] args) {
int[] arc = {1,2,5,76,8,0,6,5,1,4,8,4,6};
System.out.println(Arrays.toString(arr(arc)));
}
public static int[] arr(int[] arc) {
int indexOfTheFirstZero = -1;
// find the first 0 and store its index
for (int i=0;i<arc.length;i++){
if(arc[i] == 0) {
indexOfTheFirstZero = i;
break;
}
}
// main loop
for (int i=0;i<arc.length;i++){
// need work only if item is not 0
if(arc[i] != 0) {
for (int j=i+1;j<arc.length;j++){
if (arc[i] == arc[j]) {
arc[j] = 0;
}
}
arc[i]=1;
}
}
// change first 0 (if it exists) to 1
if(indexOfTheFirstZero != -1) {
arc[indexOfTheFirstZero] = 1;
}
return arc;
}
}
答案 1 :(得分:2)
public static int[] arr() {
int[] arc = {1, 1, 4, 6};
int[] result = new int[arc.length];
for (int i = 0; i < arc.length; i++) { // Changed 13 to arc.length
result[i] = 1; // Suppose not duplicate until proven wrong
for (int j = 0; j < i; j++) { // first element is 0, only need to check up to current elememt
if (arc[i] == arc[j]) {
result[i] = 0; // Found a duplicate. Element i should be zero
// arc[j]=0; No need to change arc[j].
break; // No need to check the rest of the array
// } else { // The else is now unnecessary
}
}
}
return result;
}