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;
        }
    }
    
  • 相关阅读:
    STL的适配器、仿函数学习之一:accumulate和for_each的使用心得
    百度笔试题--------数字拼接,求出最小的那个
    百度面试题----依概率生成
    百度笔试题----C语言版revert
    百度笔度题-----蚂蚁爬杆问题
    Try....Catch......Finally 的执行顺序
    数据库SQL SERVER 2008R2 远程连接配置说明
    C#中的数据库的连接方式分类说明(转载)
    网络通信—udp使用领悟
    (转载)C#网络通信之TCP连接
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742801.html
Copyright © 2011-2022 走看看