字符串算法——单一数(Single Number II)

来源:互联网 发布:淘宝申请客服介入处理 编辑:程序博客网 时间:2024/06/03 22:09

问题:
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?
给定一个整数数组,每个元素都出现三次,除了一个元素只出现过一次,找到那个单一数。
思路一:不考虑附加条件,可以采用暴力方法,依次对每个算法进行比较
思路二:采用异或的方法

class Solution {    public int singleNumber(int[] nums) {        int a = 0;        int b = 0;        for(int i = 0;i<nums.length;i++){            b = (b^nums[i])&~a;            a = (a^nums[i])&~b;        }        return b;    }}

对于出现奇数次的该类方法都可以用该方法。