已知:
给定一个特殊的数组,其中只包含一个单独的数,其他的数字都是成双且相互靠近出现的。求出这个单独的数。
思路:
先排除特殊情况,如果第一个数和第二个数不等,那么直接返回第一个数,倒数第一个和倒数第二个也同理。
然后,偶数位X上的数字必须与奇数位X+1上的数字相等,如果不相等,那么X上的数字就是我们要找到答案。
11 22 33 44 55 67 78 89 9
public class Solution { /** * @param nums: The number array * @return: Return the single number */ public int getSingleNumber(int[] nums) { if (nums[0] != nums[1]) { return nums[0]; } if (nums[nums.length - 1] != nums[nums.length - 2]) { return nums[nums.length - 1]; } for (int i = 2; i <= nums.length - 4; i += 2) { if (nums[i] != nums[i + 1]) { return nums[i]; } } return -1; } }