My simple JavaScript solution


  • 1
    K

    var singleNumber = function(nums) {
    nums.sort();
    for (var i = 0; i < nums.length; i += 2) {
    if (nums[i] != nums[i + 1]) {
    return nums[i];
    }
    }
    };


  • 4
    K
     var singleNumber = function(nums) {
                nums.sort();
                for (var i = 0; i < nums.length; i += 2) {
                    if (nums[i] != nums[i + 1]) {
                        return nums[i];
                    }
                }
            };
    

  • 0

    I don't know why Javascript can handle overflow when the single number is the last one in nums. e.g.: [2, 2, 3], there is no nums[i + 1], but the result is correct(3).


  • 1
    L

    For this particular case, I don't believe overflow is actually being handled at all, and we're actually relying on Javascript's inabilty to handle it to give us the answer we're looking for. Here, we're comparing the last value in a sorted array (a valid value) to a value that returns undefined (the value we get from trying to find the next index's value in the array, which does not exist). Our 'if' statement will run, as in the above example, (3 !== undefined), will return true.


Log in to reply
 

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