LC 136. Single Number

Nilanjan Deb · April 1, 2020

I solved this problem using a simple logic. Here I use the algorithm of check duplicate numbers. For some Corner cases(like zero/one elements, answer is first element) I use some if statements. I thought remainings are self-understandable.

This is my CPP solution.

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(),nums.end());
        if(n==0){
            return 0;
        }
        if(n==1){
            return nums[0];
        }
        if(nums[0]!=nums[1]){
            return nums[0];
        }
        for(int i=1;i<n-1;i++){
            if(nums[i]!=nums[i+1] && nums[i]!=nums[i-1]){
                return nums[i];
            }
        }
        return nums[n-1];
    }
};

Time Complexity O(n); Space Complexity O(1);



Dicussion Forum