第九周:137. Single Number II

来源:互联网 发布:网络歌手排行榜2005 编辑:程序博客网 时间:2024/06/10 15:24

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Subscribe to see which companies asked this question.

AC:

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


0 0