本文主要是介绍Leetcode76: Single Number II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
两种解法都是通用的,但并不是最快的。
解法一:
class Solution {
public:int singleNumber(vector<int>& nums) {if(nums.size() == 0)return 0;else if(nums.size() == 1)return nums[0];sort(nums.begin(), nums.end());for(int i = 0; i < nums.size()-1;){if(nums[i] == nums[i+1])i+=3;else{return nums[i];}if(i == nums.size()-1)return nums[i];}}
};
解法二:
class Solution {
public:int singleNumber(vector<int>& nums) {int res = 0;int bit[32] = {0};for(int i = 0; i < 32; i++){for(int j = 0; j < nums.size(); j++){bit[i] += (nums[j]>>i) & 1;}res |= (bit[i]%3)<<i;}return res;}
};
这篇关于Leetcode76: Single Number II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!