Easy C++ solution


  • 0
    U

    class Solution {
    public:
    int singleNonDuplicate(vector<int>& nums) {

        for (int i = 0; i < nums.size(); i+= 2) {
            if (nums[i] != nums[i+1]) {
                return nums[i];
                break;
            }
        }
        
    }
    

    };


  • 0
    Y

    I'm wondered what will be displayed if the array index is amount to nums.size. For example, if the single number is at the end of the array, then there is no number in the nums[i+1]. Should it be displayed "Error" when nums[i]!=nums[i+1]?


  • 0
    C

    said in Easy C++ solution:

    for (int i = 0; i < nums.size(); i+= 2) {
    if (nums[i] != nums[i+1]) {
    return nums[i];
    break;
    }
    }

        for (int i = 0; i < nums.size()-1; i+= 2)
        {
            if (nums[i] != nums[i+1])
            {
                return nums[i];
            }
        }
        
        return nums.back();

Log in to reply
 

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