zoukankan      html  css  js  c++  java
  • Single Number

    Problem I

    Given an array of integers, every element appears twice except for one. Find that single one.

    解决思路

    全部的元素进行异或,输出结果。

    Problem II

    Given an array of integers, every element appears three times except for one. Find that single one.

    解决思路

    统计出所有元素在32位上的位数之和,然后模3,得到的数即为单数。

    程序

    public class Solution {
        public int singleNumber(int[] nums) {
    		if (nums == null || nums.length == 0) {
    			return 0;
    		}
    		if (nums.length < 4) {
    			return nums[0];
    		}
    		int[] bits = new int[32];
    		int res = 0;
    		for (int i = 0; i < bits.length; i++) {
    			for (int j = 0; j < nums.length; j++) {
    				bits[i] += (nums[j] >> i) & 1;
    			}
    			res |= (bits[i] % 3) << i;
    		}
    		return res;
    	}
    }
    

    可以拓展到任意个重复元素(对K取模,设置k值)中找单个元素。

    Problem III

    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. 得到所有元素异或的结果;

    2. 得到的结果一定不为0,找到该结果的任意一位不为0的位数;

    3. 将该位与所有的元素进行与操作,分成两组;

    4. 在这两组中,单独使用Problem I中的方法即可。

    程序

    public class Solution {
        public int[] singleNumber(int[] nums) {
            if (nums == null || nums.length < 3) {
                return nums;
            }
            
            int xor = 0;
            for (int i = 0; i < nums.length; i++) {
                xor = xor ^ nums[i];
            }
            
            int rightMostOne = xor & ~(xor - 1);
            int n1 = 0, n2 = 0;
            
            for (int i = 0; i < nums.length; i++) {
                if ((rightMostOne & nums[i]) == 0) {
                    n1 = n1 ^ nums[i];
                } else {
                    n2 = n2 ^ nums[i];
                }
            }
            
            int[] singleNums = {0, 0};
            singleNums[0] = n1;
            singleNums[1] = n2;
            
            return singleNums;
        }
    }
    
  • 相关阅读:
    vue双向数据绑定原理解析及js代码实现
    react 实现tab切换
    vue不是内部或外部命令,解决办法
    JavaScript 基础知识 表达式和运算符
    JavaScript 基础知识 变量与数据类型
    Animation动画-小动画
    Ajax的封装
    esp32 python上位机(命令行)
    ESP32扫描环境中的所有WiFi并且通过串口选择需要连接的WiFi
    Linux修改开机图形/etc/motd
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742801.html
Copyright © 2011-2022 走看看