LeetCode每日一题——136. Single Number

版权声明:本文为博主原创文章,转载请附上原文链接! https://blog.csdn.net/qq_22770457/article/details/53609616

原题地址: 

https://leetcode.com/problems/single-number/



Fizz Buzz

描述

Given an array of integers, every element appears twice except for one. Find that single one.



举例


解题思路

一开始的想法是循环遍历整个数组,用一个ArrayList做增加判断,如果已经存在了就删掉,不存在就添加,这样到最后ArrayList中剩下的数就是那个单数。


不过最后在网上找到了另外一种更优解,通过异或运算进行判断,虽然都是线性的时间复杂度,不过不设计ArrayList的操作内存耗费低很多。

测试在1000000次情况下第一种方式时间耗费是339,第二种是7,可见数组操作对内存消耗是巨大的,以后应该尽量避免。


作答

public class SingleNumber {
	public static void main(String[] args) {
		int[] nums = { 1, 1, 2, 3, 3, 6, 6, 8, 8, 9, 9 ,12,12,45,45,78,78,56,56,42,32,42,32};
		System.out.println(singleNumber2(nums));
	}

	public static int singleNumber(int[] nums) {
		ArrayList<Integer> numList = new ArrayList<>();
		for (int i = 0; i < nums.length; i++) {
			if (numList.contains(nums[i])) {
				numList.remove((Integer) nums[i]);
			} else {
				numList.add(nums[i]);
			}
		}
		return numList.get(0);
	}

	//异或运算,不同的比较得0,相同的比较得1
	public static int singleNumber2(int[] A) {
		// Note: The Solution object is instantiated only once and is reused by
		// each test case.
		if (A == null || A.length == 0) {
			return 0;
		}
		int result = A[0];

		for (int i = 1; i < A.length; i++) {
			result = result ^ A[i];
		}
		return result;
	}
}


猜你喜欢

转载自blog.csdn.net/qq_22770457/article/details/53609616