题目描述:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路:
给定一个数组。只有一个数只出现了一次,别的都是两次,找出它来。
简单数学方法:XOR方法,异或。 A XOR A = 0 A XOR B = 1, A XOR 0 = A 且具有可交换性
如:(2^1^4^5^2^4^1) => ((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5
定义一个result = 0 与每个数异或计算,然后得出的结果就是那个单独的数。
如果用正常思路时间复杂度为O(n^2),***提交会超时。
思路是对每一个元素进行遍历查找是否存在,没有则返回它
1 public class Solution136 { 2 public int singleNumber(int[] nums) { 3 //异或方法解决: 4 /*int result = 0; 5 for(int i = 0; i < nums.length; i++){ 6 result = result ^ nums[i]; 7 } 8 return result;*/ 9 int result=0; 10 int j,i; 11 int n = nums.length; 12 for(i = 0;i < n;i++) 13 { 14 for(j = 0;j < n;j++) 15 { 16 if(i == j) 17 continue; 18 else if(nums[i] == nums[j]) 19 break; 20 else continue; 21 } 22 23 if(j == n) 24 return nums[i]; 25 } 26 return result; 27 28 } 29 public static void main(String[] args) { 30 // TODO Auto-generated method stub 31 int[] nums = {2,1,4,5,2,4,1}; 32 Solution136 solution136 = new Solution136(); 33 System.out.println(solution136.singleNumber(nums)); 34 } 35 36 }