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.
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
/**
*
* @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));
}
}
The only thing you did incorrectly was not resetting count to 0. However, I added a few more optimizations.
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.
}
}