Given an array of integers, every element appears three except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题意理解:
数组中除一个元素外其余元素均出三次,找出单独出现一次的数组元素。
解题思路:
1)判断输入的合法性
2)对数组元素排序(用到Arrays的排序方法)
3)每次循环取三个数比较,两两比较,若相同,则继续循环,否则单独的数即为当前索引对应的数
4)输出指定数组元素
特别提醒:
当数组元素为空时,输出0;当数组元素只有一个时,输出数组本身;当数组元素只有两个或三个时,输出0;
Given an array of integers, every element appears three except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题意理解:
数组中除一个元素外其余元素均出三次,找出单独出现一次的数组元素。
解题思路:
1)判断输入的合法性
2)对数组元素排序(用到Arrays的排序方法)
3)每次循环取三个数比较,两两比较,若相同,则继续循环,否则单独的数即为当前索引对应的数
4)输出指定数组元素
特别提醒:
当数组元素为空时,输出0;当数组元素只有一个时,输出数组本身;当数组元素只有两个或三个时,输出0;
import java.util.Arrays;
public class Solution {
public int singleNumber(int[] nums) {
int single = 0;
if (nums == null)
single = 0;
if (nums.length == 1)
single = nums[0];
if (nums.length == 2||nums.length ==3)
single = 0;
Arrays.sort(nums);
int place = 0;
while (place < nums.length) {
if (place + 2 < nums.length && nums[place + 1] == nums[place] && nums[place + 2] == nums[place])
place = place + 3;
else {
single = nums[place];
break;
}
}
return single;
}
}
Given an array of integers, every element appears three except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题意理解:
数组中除一个元素外其余元素均出三次,找出单独出现一次的数组元素。
解题思路:
1)判断输入的合法性
2)对数组元素排序(用到Arrays的排序方法)
3)每次循环取三个数比较,两两比较,若相同,则继续循环,否则单独的数即为当前索引对应的数
4)输出指定数组元素
特别提醒:
当数组元素为空时,输出0;当数组元素只有一个时,输出数组本身;当数组元素只有两个或三个时,输出0;