Leetcode_260_Single Number III

来源:互联网 发布:淘宝精品山珊瑚绒毛毯 编辑:程序博客网 时间:2024/05/29 12:47

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



Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

思路:

(1)题意为给定一个整数数组,其中有两个元素仅仅出现一次,其余所有的元素都出现两次,请找出这个两个只出现一次的元素。

(2)由于有两个元素出现了一次,就不能用^的方法进行解决。这里需要借助一个Map来实现,其中key为数组中元素,value为该元素在数组中出现的次数。首先,遍历数组,若遍历的当前元素不在map中,则将当前元素存入map中,value置为1;若存在于map中,则将其对应的value值加1。这里还设置一变量存储所遍历元素在数组中个数大于2的元素数量。其次,创建一个数组,数组大小为原数组长度减去存储的变量数值,然后遍历map,将map中value值为1的元素依次存入创建的数组中,即为所求。

(3)详情见下方代码。希望本文对你有所帮助。


算法代码实现如下:

import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;public class Single_Number_III {public static void main(String[] args) {singleNumber(new int[] { 0, 0, 1, 2 });}public static int[] singleNumber(int[] nums) {if (nums == null || nums.length == 0)return nums;int len = nums.length;int p = 0;Map<Integer, Integer> maps = new LinkedHashMap<Integer, Integer>();for (int i = 0; i < len; i++) {if (maps.get(nums[i]) == null) {maps.put(nums[i], 1);} else {maps.put(nums[i], maps.get(nums[i]) + 1);p = p + maps.get(nums[i]);}}int[] arr = new int[len - p];int t = 0;Set<Integer> keySet = maps.keySet();for (Integer integer : keySet) {if (maps.get(integer) == 1) {arr[t++] = integer;}}return arr;}}


1 0
原创粉丝点击