136. 只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
public class Solution {public int singleNumber(int[] nums) {int res;for (int n:nums) {res ^= n;}return res;}}
137. 只出现一次的数字 II
给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。
public class Solution {public int singleNumber(int[] nums) {int res = 0;Map<Integer,Integer> map = new HashMap<>();for (int n:nums) {map.put(n,map.getOrDefault(n,0) + 1);}for (Map.Entry<Integer,Integer> en:map.entrySet()) {int k = en.getKey();int v = en.getValue();if (v == 1) {res = k;break;}}return res;}}
260. 只出现一次的数字 III
给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。
输入:nums = [1,2,1,3,2,5] 输出:[3,5] 解释:[5, 3] 也是有效的答案。
public class Solution {public int singleNumber(int[] nums) {int index = 0;int[] res = new int[2];Map<Integer,Integer> map = new HashMap<>();for (int n:nums) {map.put(n,map.getOrDefault(n,0) + 1);}for (Map.Entry<Integer,Integer> en:map.entrySet()) {int k = en.getKey();int v = en.getValue();if (v == 1) {res[index++] = k;}}return res;}}
