首页IT科技数组中有一个数字出现的次数超过了(每日算法之数组中只出现一次的两个数字)

数组中有一个数字出现的次数超过了(每日算法之数组中只出现一次的两个数字)

时间2025-08-04 21:58:20分类IT科技浏览6467
导读:JZ56 数组中只出现一次的两个数字 题目...

JZ56 数组中只出现一次的两个数字

题目

一个整型数组里除了两个数字只出现一次                 ,其他的数字都出现了两次                。请写程序找出这两个只出现一次的数字

思路

算法实现

既然有两个数字只出现了一次                        ,我们就统计每个数字的出现次数        ,利用哈希表的快速根据key值访问其频率值                         。

具体做法:

step 1:遍历数组             ,用哈希表统计每个数字出现的频率        。

step 2:然后再遍历一次数组                        ,对比哈希表            ,找到出现频率为1的两个数字            。

step 3:最后整理次序输出                         。

代码

package mid.JZ56数组中只出现一次的两个数字; import java.util.*; public class Solution { /** * 代码中的类名                 、方法名                        、参数名已经指定         ,请勿修改                         ,直接返回方法规定的值即可 * * * @param array int整型一维数组 * @return int整型一维数组 */ public int[] FindNumsAppearOnce (int[] array) { // write code here if(array.length == 0) return new int[0]; HashMap<Integer, Integer> map = new HashMap<>(); int[] result = new int[2]; for (int value : array) { if (!map.containsKey(value)) { map.put(value, 1); } else { map.put(value, map.get(value) + 1); } } int index = 0; for (Integer key: map.keySet()) { if (map.get(key) == 1) { result[index] = key; index++; } if (index == 2) break; } Arrays.sort(result); return result; } public static void main(String[] args) { int[] ints = new Solution().FindNumsAppearOnce(new int[]{1, 4, 1, 6}); System.out.println(Arrays.toString(ints)); } }

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
php打断点(php命令行中进行断点) 打工怎么赚钱快?(如何打工可以发财呢-打工越多,赚钱越少。)