Java 检查数组中备用项的最有效方法
我有一个10000大小的int数组,它只由1和0组成Java 检查数组中备用项的最有效方法,java,arrays,Java,Arrays,我有一个10000大小的int数组,它只由1和0组成 String str="101010101010101010101001010101010101011110000000000001101010101101......" 我的任务是检查此数组是否有备用项 我这样试过: Case 1: Case 2: //when str=010101010.....
String str="101010101010101010101001010101010101011110000000000001101010101101......"
我的任务是检查此数组是否有备用项
我这样试过:
Case 1: Case 2:
//when str=010101010..... //when str=101010101.....
boolean cha =true; boolean ch=true;
for(int j=0;j<n;j++) for(int j=0;j<n;j++)
{ {
if(j%2==0) if(j%2==1)
{ {
if(arr[j]==1) if(arr[j]==0)
cha=false; cha=true;
} }
if(j%2==1) if(j%2==0)
{ {
if(arr[j]==0) if(arr[j]==1)
cha=false; ch=false;
} }
if(cha==false) if(ch==false)
break; break;
} }
if(cha==true) if(ch==true)
System.out.println("YES"); System.out.println("YES");
案例1:案例2:
//当str=010101010时//当str=101010101时。。。。。
布尔值cha=true;布尔值ch=真;
对于(int j=0;j而言,最简单的方法可能是对照前两个元素验证所有元素:
// Replace this with a better test if you can have something other than 0 and 1
if(arr[0] + arr[1] != 1) {
cha = false;
} else {
for(int i = 2; i < arr.length; i++) {
if(arr[i] != arr[i % 2]) {
cha = false;
break;
}
}
}
//如果可以使用0和1以外的内容,请使用更好的测试替换此测试
如果(arr[0]+arr[1]!=1){
cha=假;
}否则{
对于(int i=2;i
如果偶数元素不等于arr[0]
中的任何元素,则cha
将被设置为false
,因为i%2
对于偶数元素将始终为零。奇数元素和arr[1]
您可以使用正则表达式:
String pattern = "^(10)+1{0,1}$|^(01)+0{0,1}$";
String s1 = "01010101";
String s2 = "101010101";
String s3 = "11001111";
s1.matches(pattern); // return true
s2.matches(pattern); // return true
s3.matches(pattern); // return false
对于那些对“streamy”Java 8解决方案感兴趣的人:
int[] input = ..... // your array
// create an IntStream with the values of the input array at the even indices ...
// ... then get the unique elements and count how many you have
long countEven = IntStream.range(0, input.length)
.filter(n -> n % 2 == 0).map(i -> input[i]).distinct().count();
// do the same for the uneven indices
long countUneven = IntStream.range(0, input.length)
.filter(n -> n % 2 != 0).map(i -> input[i]).distinct().count();
// if the even/uneven indices contain 1 unique element each,
// ... the array contains alternating numbers
if (countEven == 1L && countUneven == 1L) System.out.println("alternating 1s and 0s!");
您所拥有的没有多大意义。无论j%2
是1还是0,您都设置了cha=false
。在这两种情况下,字符串部分的位置也不清楚,因为您没有使用它(或数组)在你的循环中…#我只是想展示我的数组的外观,这就是我使用它的原因@Jonsket但给定的代码没有任何意义,这应该是什么,你只是在n上迭代,除了检查它%。@kunjalrupala。你的代码不检查数组的元素,只检查索引。@MadPhysicar,她说他将其转换为字符串,因此使用字符串来执行此操作否,OP将其转换为字符串以向我们展示其外观。@kunjalrupala。抱歉。无意冒犯。@MadPhysicator,“当我将其转换为字符串时,它看起来像这样…”所以她有字符串表示法,这个代码可以work@ThibautB.很公平。反对被撤销。这是一个很好的方法,尤其是当它保持int[]
如前所述。我确实认为对它的工作原理进行一点解释会有所帮助。此外,也许还可以对这种方法的效率进行一点说明。我添加了一点解释。很难说性能。如果数组的字符串表示形式已经存在,则使用string的解决方案与UT执行此解决方案。如果考虑创建字符串,它将取决于从int[]
到string
所使用的方法,当数组变大时,我的方法将开始赶上或做得更好。