From 34e7e015c77c06d1c34dca67f7a23899299cd101 Mon Sep 17 00:00:00 2001 From: zeekling Date: Sun, 29 Nov 2020 16:24:03 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=AA=E5=87=BA=E7=8E=B0=E4=B8=80=E6=AC=A1?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/leetcode/array/SingleNumber.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/com/leetcode/array/SingleNumber.java diff --git a/src/main/java/com/leetcode/array/SingleNumber.java b/src/main/java/com/leetcode/array/SingleNumber.java new file mode 100644 index 0000000..80fe2b7 --- /dev/null +++ b/src/main/java/com/leetcode/array/SingleNumber.java @@ -0,0 +1,53 @@ +package com.leetcode.array; + +import java.util.HashMap; +import java.util.Map; + +/** + * 只出现一次的数字 +给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 + +说明: + +你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? + +示例 1: + +输入: [2,2,1] +输出: 1 +示例 2: + +输入: [4,1,2,1,2] +输出: 4 + +作者:力扣 (LeetCode) +链接:https://leetcode-cn.com/leetbook/read/top-interview-questions/xm0u83/ +来源:力扣(LeetCode) +著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 + */ +public class SingleNumber { + + + public int singleNumber(int[] nums) { + Map map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + Integer counter = map.getOrDefault(nums[i], 0); + counter ++; + map.put(nums[i], counter); + } + for (Map.Entry entry: map.entrySet()) { + if (entry.getValue() == 1) { + return entry.getKey(); + } + } + return 0; + } + + public static void main(String[] args) { + SingleNumber singleNumber = new SingleNumber(); + int[] nums = {2,2,1}; + int res = singleNumber.singleNumber(nums); + System.out.println(res); + } +} -- 2.45.2