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;
        }
    }
  • 相关阅读:
    OO第四单元总结
    OO第三单元总结
    回首萧瑟处——软工学期回顾总结
    折腾Linux内核编译
    偷梁换柱:使用mock.patch辅助python单元测试
    OCR-Form-Tools项目试玩记录(二)产品评测
    OCR-Form-Tools项目试玩记录(一)本地部署
    软工个人项目-求交点数目
    软工个人博客作业:阅读、提问与一些调研
    我拒绝同自己和解·软工第一次作业
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4741051.html
Copyright © 2011-2022 走看看