Search code examples
javaarraysnested-loops

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.

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));
    }
    
}

Solution

  • The only thing you did incorrectly was not resetting count to 0. However, I added a few more optimizations.

    • as soon as count exceeds 1, stop the inner loop and continue the outer one
    • if the inner loop continues successfully, you know that count was only 1 so you can immediately return tmp.
    • if you completely finish the outer loop, that means no values occurred just once, so return -1. This means that -1 should not be a legitimate value. If it is, some other method of showing this should be used.
    • finally, if more than one value occurs once, only the first will be returned.
    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.
        }
    }