Fork me on GitHub

single-number

/**
* @author gentleKay
* 题目描述
* 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?
* 给定一个整数数组,除一个元素外,每个元素都出现两次。找到那个。
* 注:
* 您的算法应该具有线性运行时复杂性。你能在不使用额外内存的情况下实现它吗?
*/

方法一:(用异或运算)

使用异或运算之前我们先了解一下,异或运算:

public class Demo {
	public static void main(String[] args) {
		System.out.println(5^5);  	  // 0   相同的两个数 进行异或运算为 0
		System.out.println(8^8);  	 // 0  
		System.out.println(5^8^5^8);    // 0  一些数进行异或运算, 里面包含两个数是相同的, 
		System.out.println(0^3); 	 // 3  任何整数 = 0^任何整数
		System.out.println(5^8^5^8^3);  // 3 
	}
}

接下来,有了一点基础之后进行题目解析,这样题目显得十分简单:

/**
 * 
 * @author gentleKay
 * 题目描述
 * 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?
 * 给定一个整数数组,除一个元素外,每个元素都出现两次。找到那个。
 * 注:
 * 您的算法应该具有线性运行时复杂性。你能在不使用额外内存的情况下实现它吗?
 */

public class Main05 {
	public static void main(String[] args) {
		int[] A = {17,12,5,-6,12,4,17,-5,2,-3,2,4,5,16,-3,-4,15,15,-4,-5,-6};
		System.out.println(Main05.singleNumber(A));
		
		//System.out.println(2^3^4^5^6^7^8^2^3^4^5^6^7^8^9^9);  //使用异或运算 循环叠加 。
	}
	
	public static int singleNumber(int[] A) {
		int a = A[0];
		for (int i=0;i<A.length;i++) {
			a = a ^ A[i];
		}
		return a;
    }
}

方法二:(Set集合)

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 
 * @author gentleKay
 * 题目描述
 * 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?
 * 给定一个整数数组,除一个元素外,每个元素都出现两次。找到那个。
 * 注:
 * 您的算法应该具有线性运行时复杂性。你能在不使用额外内存的情况下实现它吗?
 */

public class Main05 {
	public static void main(String[] args) {
		int[] A = {17,12,5,-6,12,4,17,-5,2,-3,2,4,5,16,-3,-4,15,15,-4,-5,-6};
		System.out.println(Main05.singleNumber(A));
		
	}
	
	public static int singleNumber(int[] A) {
      Set<Integer> set = new HashSet<>();
      int[] a = new int[1];
		for (int i=0;i<A.length;i++) {
			if (!set.contains(A[i])) {
				set.add(A[i]);
			}else {
				set.remove(A[i]);
			}
		}
		Iterator<Integer> it = set.iterator();
		while (it.hasNext()) {
			return it.next();
		}
		return 0;

    }
}

  

posted @ 2019-07-23 14:53  gentleKay  阅读(193)  评论(0)    收藏  举报