zoukankan      html  css  js  c++  java
  • Single Number III——LeetCode

    Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

    For example:

    Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

    Note:

    1. The order of the result is not important. So in the above example, [5, 3] is also correct.
    2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

    题目大意:一个数组,有两个元素出现了一次,其余元素都出现两次,让用线性时间复杂度和常量空间复杂度找出这两个数。

    解题思路:考虑位操作,对所有元素做异或操作,那么最后得到的值就是要求的两个元素异或得到的,那么找出其中为1的某一位,说明这一位两个数一个为0,一个为1,以这一位为标准,把数组的元素分为两组A、B,那么要求的两个元素肯定是一个在A组,一个在B组,而对这两组各自做异或操作,就可以得到两个数就是要求的。

    public class SingleNumberIII {
    
        public static void main(String[] args) {
            int[] res = singleNumber(new int[]{1, 2, 1, 3, 5, 2});
            System.out.println(Arrays.toString(res));
        }
    
        public static int[] singleNumber(int[] nums) {
            int[] res = new int[2];
            if (nums == null || nums.length == 0) {
                return res;
            }
            for (int i = 0; i < nums.length; i++) {
                res[0] ^= nums[i];
            }
            int pos = 0;
            for (int i = 0; i < 32; i++) {
                int offset = 1 << i;
                if ((res[0] & (offset)) == offset) {
                    pos = i;
                    break;
                }
            }
            res[0] = 0;
            int mask = 1 << pos;
            for (int i = 0; i < nums.length; i++) {
                if ((mask & nums[i]) == mask) {
                    res[0] ^= nums[i];
                } else {
                    res[1] ^= nums[i];
                }
            }
            return res;
        }
    }
  • 相关阅读:
    Python自定义web框架、Jinja2
    Django初探(模板渲染、模板语音、simple_tag、母版子版、静态配置文件)
    多线程 threading
    python操作mysql
    sql 汉字转首字母拼音
    添加sql server约束
    NFS,Memcached,Tokyo tyrant实现session共享性能测试
    让Editplus自动格式化js、css、html。。。
    sql server中利用sql语句如何创建角色和用户
    asp网站文件夹权限设置
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4741051.html
Copyright © 2011-2022 走看看