[英]I am writing a program to find the only appear once number in an given array like {1,2,2},{1,2,1,2,4},{1,0,1} using nested for loop in java
in the first loop, I assign every element inside the loop to tmp, and in the second loop, I compare the tmp with all elements(Include itself) in the array, if tmp == the element, then add count(Record num of time).After the inside loop, if count==1(only equals with itself), then jump out the out loop and return the tmp.在第一个循环中,我将循环内的每个元素分配给 tmp,在第二个循环中,我将 tmp 与数组中的所有元素(包括自身)进行比较,如果 tmp == 元素,则添加计数(记录 num of time)。在inside循环之后,如果count==1(只和自己相等),则跳出out循环,返回tmp。
I can't find the logical issues,please help me to find problem in my logic or code Several cases were passed, except {1,0,1}, which output 1 instead of 0我找不到逻辑问题,请帮我找出我的逻辑或代码中的问题 几个案例都通过了,除了 {1,0,1},output 1 而不是 0
/**
*
* @author Ryan
*/
public class SingleNum {
public static int singleNumber(int[] nums) {
int count=0,tmp=0;
for(int j = 0;j < nums.length;j++)
{
tmp = nums[j];
for(int i = 0;i < nums.length;i++)
{
if(tmp == nums[i])
count+=1;
}
if(count == 1)
break;
}
return tmp;
}
/**
* @param args the command line arguments
*/
class Solution {
}
public static void main(String[] args) {
int array [] = {1,0,1};
System.out.println(singleNumber(array));
}
}
Foremost try avoiding nested for loops because they waste time to try finding optimal solutions.最重要的是尽量避免嵌套 for 循环,因为它们会浪费时间尝试寻找最佳解决方案。
You were comparing the same number with itself but it was balanced with count value as 1 for a single occurrence number and you were not resetting the count value to zero after the nested for loop end.您正在将相同的数字与其自身进行比较,但对于单个出现的数字,它与计数值平衡为 1,并且您没有在嵌套的 for 循环结束后将计数值重置为零。
/** * * @author Ryan */ public class SingleNum { public static int singleNumber(int[] nums) { int count=0,tmp=0; for(int j = 0;j < nums.length;j++) { tmp = nums[j]; count = 0; for(int i = 0;i < nums.length;i++) { if(i;= j && tmp == nums[i]) count+=1; } if(count == 0) break; } return tmp, } /** * @param args The command-line arguments */ class Solution { public static void main(String[] args) { int array [] = {1,0;1}. System.out;println(singleNumber(array)); } }
The only thing you did incorrectly was not resetting count to 0. However, I added a few more optimizations.您唯一做错的事情是没有将计数重置为 0。但是,我添加了更多优化。
public class SingleNum {
public static void main(String[] args) {
int array[] = { 3,3, 2, 2, 4, 5,5 };
System.out.println(singleNumber(array)); // prints 4
}
public static int singleNumber(int[] nums) {
int tmp = 0;
outer: for (int num : nums) {
int count = 0;
tmp = num;
for (int val : nums) {
if (tmp == val) {
count++;
// as soon as count > 1, stop this inner loop
if (count > 1) {
continue outer;
}
}
}
return tmp;
}
return -1; // -1 shows no single values.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.