• 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;
        }
    }
    
  • 相关阅读:
    jquery 实现弹出框 打开与关闭
    原生 将数组内容分别存入创建的循环单行栏(复选框+内容)里 并验证
    利用jquery 实现单页定位动画运动
    CSS样式 鼠标状态
    cookie 的使用:打开集团站自动跳转到当前城市所对应的网站,通过改变城市跳转到当前城市所对应的网站
    表单验证--通过原生js模仿ajax的异步交互
    springMVC之单文件上传
    springMVC之普通表单提交
    分页之页码数量显示
    cron表达式详解
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742801.html
Copyright © 2020-2023  润新知