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;
        }
    }
    
  • 相关阅读:
    glib文档
    2020第42周面向失败设计
    2020第41周中年危机焦虑
    2020第40周选合适的工具
    2020第39周微行动思维
    2020第38周
    2020第37周
    2020第36周
    2020第35周不要让孩子输在起跑线
    2020第34周滥竽充数
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742801.html
Copyright © 2011-2022 走看看