再来一道,刷简单题。
137. Single Number II
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?
题目思路和136一致,只需要将步长设为3即可,分析过程见我blog
http://leonard1853.iteye.com/blog/2275626
public class Solution {
public int singleNumber(int[] nums) {
Arrays.sort(nums);
int index = 0;
while(index < nums.length - 2) {
if (nums[index] - nums[index + 1] == 0 && nums[index] - nums[index + 2] == 0) {
index += 3;
} else {
return nums[index];
}
}
return nums[index];
}
}