Single Number II

来源:互联网 发布:oracle数据库账号密码 编辑:程序博客网 时间:2024/05/17 13:06

题目地址:https://leetcode.com/problems/single-number-ii/

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

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

这个题目有点意思,如果是让开辟新空间的话,那这个题目也没啥难度,计个数就可以了,但是如果用O(1)的空间来搞定的话,就要稍微想一下了。

题目中说在给的的数组中,只有一个元素出现过一次,其他的都出现3次,那么如何找出这个只出现过一次的元素呢?

我们知道如果把每个整数转为32位的二进制数,然后把这32位放到一个长度为32的数组中,那么相同的3个数字相加后,数组中的每一个元素肯定是3,对3求余则为0,所有的数字加进来,然后对3求余,那么结果肯定是那个独一存在的数字的二进制数,有了这个想法,那么代码就好写多了:

public class SingleNumberII {    public int singleNumber(int[] nums) {        int[] count = new int[32];        for (int i = 0; i < 32; i++)            count[i] = 0;        int result = 0;        for (int i = 0; i < 32; i++) {            for (int j = 0; j < nums.length; j++) {                if (((nums[j] >> i) & 1) != 0) {                    count[i]++;                }            }            result |= ((count[i] % 3) << i);        }        return result;    }}
0 0
原创粉丝点击