• 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;
        }
    }
    
  • 相关阅读:
    Tornado 和 Gin 框架性能实测
    测试基础
    计算机基础
    跨域和CORS
    Django之Form和ModelForm组件
    Django之锁和事务,中间件
    Django之Ajax
    Django基础之ORM多表操作
    Django基础之cookie和session
    Django基础之ORM单表操作
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742801.html
Copyright © 2020-2023  润新知