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

    题意就是,给定一个数组,除了一个元素只出现一次,其他的元素全部出现三次,这个题是在另外一个题的基础上改的,另外一个题是其他元素出现2次,那么用异或操作即可。

    如果不用map或set来做,那么只能通过对数字进行操作。

    这个题目,既然给定了integer,那么还是利用位操作的思想,把每一位的值(0或1)加起来,对每一位对3取模,余下的就是只出现一次的数。

    Talk is cheap>>

       public int singleNumber(int[] A) {
            int[] res = new int[32];
            for (int i = 0; i < 32; i++) {
                for (int j = 0; j < A.length; j++) {
                    res[i] += A[j]>>i & 1 ;
                }
                res[i] %= 3;
            }
            int ret = 0;
            for (int i = 0; i < 32; i++) {
                ret |= res[i] << i;
            }
            return ret;
        }
  • 相关阅读:
    Remote API(RAPI)之 文件管理
    vue前端框架

    托马斯彩色回旋
    VUE?
    cookie与session
    ajax前后端分离
    djangoIII
    Django少年
    django三板斧
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4374250.html
Copyright © 2011-2022 走看看