Leetcode_137_Single Number II

来源:互联网 发布:字数统计 英文编程 编辑:程序博客网 时间:2024/06/09 01:09

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42877129



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

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


思路:

(1)题意为给定一个整数数组,里面除了一个元素出现一次,其余每个元素都出现了三次,找出出现一次的元素。

(2)这道题和Single Number类似,不过Single Number中是除了一个元素出现一次外,其余的都出现两次,这种情况可以直接用‘^’符号进行处理就行。但对于本题,由于技术有限,目前还没有想到比较简单的办法。本文下方采用的方法是可行的,只不过会占用额外的空间。

(3)本文解决该题的思想是:创建Map来保存数组中元素和元素出现的次数,在遍历数组的过程中,将出现的数字都存入Map中,这里还需进行一步过滤操作,就是每当遍历到的元素在Map中对应的值大于1时,就将该值保存到过滤List中,并从Map中移除该值,在后续的遍历中,如果遍历到的值存在于过滤List中,则跳过当前元素遍历下一元素,Map中最后剩余的元素即为出现一次的那个元素。

(4)希望本文对你有所帮助。



算法代码实现如下:

/** * @author liqq */public int singleNumber(int[] A) {if (A == null || A.length == 0)return -1;if (A != null && A.length == 1)return A[0];Map<Integer, Integer> maps = new HashMap<Integer, Integer>();List<Integer> filter = new ArrayList<Integer>();for (int i = 0; i < A.length; i++) {if (i == 0) {maps.put(A[i], 1);} else {if (!filter.contains(A[i])) {if (maps.get(A[i]) == null) {maps.put(A[i], 1);} else {maps.put(A[i], maps.get(A[i]) + 1);}if (maps.get(A[i]) > 1) {maps.remove(A[i]);filter.add(A[i]);}}}}return maps.keySet().toArray(new Integer[0])[0];}



1 0