题目:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
链接:https://leetcode.com/problems/single-number-ii/#/description
6/10/2017
用extra space
1 public class Solution { 2 public int singleNumber(int[] nums) { 3 Map<Integer, Integer> count = new HashMap<Integer, Integer>(); 4 5 for (int i = 0; i < nums.length; i++) { 6 count.put(nums[i], count.getOrDefault(nums[i], 0) + 1); 7 } 8 for (Map.Entry<Integer, Integer> entry : count.entrySet()) { 9 if (entry.getValue() == 1) { 10 return entry.getKey(); 11 } 12 } 13 return -1; 14 } 15 }
不会不用extra space的
很详细的解释,但是只能耐心看完m和k部分,p部分的分析没耐心看完了。他的后来的几个例子还是不错的。
更多讨论