Leetcode_single-number-ii

地址:http://oj.leetcode.com/problems/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(int A[], int n) {
        sort(A, A+n);
        for(int i = 0; i < n; ++i)
        {
            if(i==0)
            {
                if(A[i] != A[i+1])
                {
                    return A[i];
                }
            }
            else if(i==n-1)
            {
                if(A[i] != A[i-1])
                {
                    return A[i];
                }
            }
            else if(A[i] != A[i-1] && A[i] != A[i+1])
            {
                return A[i];
            }
        }
    }
};


//int有32bit位,每位检测,如果出现1次或者4次,那么仅出现一次的数在这个bit位上肯定是1.


 
 
//SECOND TRIAL
class Solution {
public :
     int singleNumber ( int A [], int n ) {
         int ans = 0 , bit_check = 0 , bit_cnt = 0 ;
         for ( int i = 0 ; i <= 31 ; ++ i )
         {
             bit_check = 1 << i ;
             bit_cnt = 0 ;
             for ( int j = 0 ; j < n ; ++ j )
                 if ( A [ j ] & bit_check )
                     ++ bit_cnt ;
             if ( bit_cnt % 3 )
                 ans |= bit_check ;
         }
         return ans ;
     }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值