5ms java solution


  • -7
    M
    	public int[] singleNumber(int[] nums) {
    	int[] rs = new int[2];
    	int count = 0;
    	Arrays.sort(nums);
    	for (int i = 0; i < nums.length - 1;) {
    		if (nums[i] != nums[i + 1]) {
    			rs[count] = nums[i];
    			count++;
    			i = i + 1;
    		} else {
    			i = i + 2;
    		}
    	}
    	if(count==1){
    		rs[1] = nums[nums.length-1];
    	}
    	return rs;
    }

  • 0
    C

    In my understanding, this way may not efficient.

    But It does take 5ms to pass all the test case that is unbelievable,

    my question is what is the magic in Array.sort in Java or the testcases are different?

    following c++ code takes 28ms:

    vector<int> singleNumberII3(vector<int>& nums) {
        std::sort(nums.begin(), nums.end());
        
        int rs[2];
        int count = 0;
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i - 1] != nums[i]) {
                rs[count++] = nums[i - 1];
            }
            else {
                ++i;
            }
        }
        if (count == 1) rs[1] = nums[nums.size() - 1];
    
        return vector<int>{rs[0], rs[1]};
        }  
    

  • 0
    M

    Array.sort in Java has its own mathmetical algorithm.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.