Leetcode_260_Single Number III

97 篇文章 0 订阅
93 篇文章 0 订阅

本文是在学习中的总结,欢迎转载但请注明出处: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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值