zoukankan      html  css  js  c++  java
  • LeetCode 笔记26 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?

    没辙,智商碾压题。楼主没遇到之前就只会这种做法。

    public int singleNumber(int[] A) {
            Map<Integer, Integer> counters = new HashMap<>();
            for(int i = 0; i < A.length; i++) {
                if (!counters.containsKey(A[i])) {
                    counters.put(A[i], 1);
                } else {
                    counters.put(A[i], counters.get(A[i]) + 1);
                }
            }
            
            for (Integer key : counters.keySet()) {
                if (counters.get(key) == 1) {
                    return key;
                }
            }
            throw new RuntimeException("no single number");
        }

    而后我们知道可以先声明个长度32的整形数组,int[32]。第i个元素存放“这些整数第i位的1的个数除以三的余数”。好拗口是不是?

    public int singleNumber2(int[] A) {
            int[] counter = new int[32];
            int ret = 0;
            for(int i = 0; i < 32; i++) {
                for (int j = 0; j < A.length; j++) {
                    counter[i] += (A[j] >> i) & 1;
                }
                ret |= (counter[i] % 3) << i;
            }
            return ret;
        }

    看了代码其实也不是“不明觉厉”。因为assume只有一个数出现一次,其他都出现3次,那么那个single number的第i位就是余下的那个数。

    。。。

    楼主中文不好。

    btw,还有一个不是很直观的位操作方法。贴这里吧,不过没做过这个的感觉很难想到。

    http://oj.leetcode.com/discuss/857/constant-space-solution 

  • 相关阅读:
    发现另一种简便的完全居中css写法 element.style { width: 500px; height: 200px; background: #eee; position: absolute; margin: auto; top: 0; left: 0; bottom: 0; right: 0; }
    子网掩码随笔
    C# MVC网站自动由HTTP转为HTTPS
    c++中的void*
    权利的游戏
    字符串
    字符串
    权利的游戏 S0803
    加权有向图
    加权无向图
  • 原文地址:https://www.cnblogs.com/lichen782/p/4304406.html
Copyright © 2011-2022 走看看