95. 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?

分析:给出的是一个数组,在这个数组中除了一个元素出现一次之外其他的元素都是出现三次,找到这个值出现一次的元素。

/**
	 * 给出的是一个数组,在这个数组中除了一个元素出现一次之外其他的元素都是出现三次,找到这个值出现一次的元素。 
	 */
	public int singleNumber(int[] nums) {
		/*首先对数组元素进行排序*/
		Arrays.sort(nums);
		/*因为只有一个元素出现一次,所以每三个元素中前两个不一样的第一个即为所要找的那个元素*/
		for(int i=0;i<nums.length-1;i=i+3){
			if(nums[i]!=nums[i+1]){
				return nums[i];
			}
		}
		return nums[nums.length-1];
    }


你可能感兴趣的:(95. Single Number II)