Given an array of integers, every element appearstwiceexcept for one. Find that single one.
Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
看到這種題第一個想法就是hashset啊哈哈哈。
根據hashset的特性,如果hashset.add()失敗的話,證明這里面已經有了一個相同的值,就是說這個number不是single number了。
所以我們判斷出【不是single number】的number再將它們從hashset里面移除,那么剩下的就是我們要找的single number了。
因為最后答案single number是在hashset中,我們并不能直接返回hashset,所以這里我們要借助iterator中的iterator().next()method。
代碼如下。~
public class Solution { public int singleNumber(int[] nums) { HashSet<Integer> set = new HashSet<Integer>(); for(int i=0;i<nums.length;i++){ if(!set.add(nums[i])){ set.remove(nums[i]); } } return set.iterator().next(); }}新聞熱點
疑難解答