1. Description
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?
2. Runtime Distribution
3. Submission Details
4. Example
Input: 14,14,14,35,23, 23,23
Ouput: 35
5. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int result = 0;
for (int k = 0; k < 32; k++) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
count += ((nums[i] >> k) & 1);
count %= 3;
}
if (count == 1) {
result |= (count << k);
}
}
return result;
}
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
public class LeetCode0137 {
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int result = 0;
for (int k = 0; k < 32; k++) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
count += ((nums[i] >> k) & 1);
count %= 3;
}
if (count == 1) {
result |= (count << k);
}
}
return result;
}
public static void main(String[] args) {
int[] nums = { 1, 1, 1, 3, 3, 3, 4 };
LeetCode0137 leetcode = new LeetCode0137();
System.out.println(leetcode.singleNumber(nums));
}
}
[/restab]
[/restabs]



Comments | NOTHING