题目:
Given an array of integers, every element appears twice except for one. Find that single one.
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
重点解析:
- 不能用额外的存储结构
- 返回结果仅有一个数,当得到的时候立刻返回
代码:
public static int singleNumber(int[] nums) { int intResult = -1; int intFlag = 0; for(int i =0;i<nums.length;i++){ intFlag = 0; for(int j=0;j<nums.length;j++){ if(nums[i] == nums[j]){ intFlag++; } } if(intFlag == 1){ return nums[i]; } } return intResult; }
时间消耗:Runtime: 804 ms
错误分析:
代码中进行了两次循环,耗时长。需要使用“异或”运算提升算法
修改后的代码:
public static int singleNumber(int[] nums) { if(nums == null || nums.length ==0){ return 0; } int intResult = 0; for(int i =0;i<nums.length;i++){ intResult = intResult ^ nums[i]; } return intResult; }
时间消耗:Runtime: 428 ms