0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode日本語修行17日目- [137-一回だけ現れった数字II]

Posted at

###Single Number II
参考:https://leetcode.com/problems/single-number-ii/
###問題の内容:
整数配列nums,1つの要素が1回現れる、それ以外、すべての要素が3回現れる、1回現れる1つの要素を除いて
その要素を見つけ、それを返す。
###例:
例1:
Input: nums = [2,2,3,2]
Output: 3
例2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
###ヒント:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
numsの中、1回だけ現れる要素を除いて、各要素はちょうど3回現れます。


この問題の回答は、2進数変換を使うなら、解決できます。
**var cnt = IntArray(32)**をつくて、nums中の数字を2進数に変換して、入ります。
例1:
Input: nums = [2,2,3,2]
00...10
00...10
00...11
00...10
cntに入れった後、
cntは
00...41
そのあと、mod3を計算して、結果は
00...11,この結果を10進数に変換、結果は3です。


class Solution {
    fun singleNumber(nums: IntArray): Int {
        var cnt = IntArray(32)
        for(num in nums){
            for(i in 0 until 32){
                if(((num.shr(i)) and 1) == 1){
                    cnt[i]++
                }
            }
        }

        var ans = 0
        for(i in 0 until 32){
            if((cnt[i] % 3 and 1) == 1){
                ans += (1.shl(i))
            }
        }
        return ans
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?