Leetcode-SingleNumberII

来源:互联网 发布:爱之谷商城源码 编辑:程序博客网 时间:2024/06/06 02:46

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

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

public class SingleNumberII {public int singleNumberII(int A[]){int bitInt[] = new int[32];//给数组初始化for (int i = 0; i<32; i++){bitInt[i] = 0;}         int result=0;          for(int i=0; i<32; i++){              for(int j=0; j<A.length; j++){              bitInt[i]+=(A[j]>>i)&1;              }              result|=(bitInt[i]%3)<<i;          }          return result;  }}

Junit单元测试:

public class SingleNumberIITest {SingleNumberII s;@Beforepublic void setUp() throws Exception {}@Afterpublic void tearDown() throws Exception {}@Testpublic void testSingleNumberII() {s = new SingleNumberII();//int B[] = {43,16,45,89,45,-2147483648,45,2147483646,-2147483647,-2147483648,43,2147483647,-2147483646,-2147483648,89,-2147483646,89,-2147483646,-2147483647,2147483646,-2147483647,16,16,2147483646,43};int B[] = {-1,2,2,2};int result = s.singleNumberII(B);//assertEquals(2147483647, result);assertEquals(-1,result);//fail("Not yet implemented");}}

说明:这种方法是一种通用的解决方法;

知识:左移、右移i位的含义(正负数相同);

          &与|跟左移、右移的结合使用;

难点:考虑到输入数据有负数的情况。

0 0
原创粉丝点击