3

#yyds干货盘点# 面试必刷TOP101:数组中只出现一次的两个数字

 2 years ago
source link: https://blog.51cto.com/u_15488507/5683106
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# 面试必刷TOP101:数组中只出现一次的两个数字

精选 原创

97的风 2022-09-16 15:49:51 博主文章分类:面试题 ©著作权

文章标签 遍历数组 数组 i++ 文章分类 Java 编程语言 阅读数185

1.简述:

描述

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

数据范围:数组长度 ,数组中每个数的大小 要求:空间复杂度 ,时间复杂度 

提示:输出时按非降序排列。

示例1
[1,4,1,6]
[4,6]
返回的结果中较小的数排在前面
示例2
[1,2,3,3,2,9]
[1,9]

2.代码实现:

import java.util.*;
public class Solution {
public int[] FindNumsAppearOnce (int[] array) {
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
//遍历数组
for(int i = 0; i < array.length; i++)
//统计每个数出现的频率
if(!mp.containsKey(array[i]))
mp.put(array[i], 1);
else
mp.put(array[i], mp.get(array[i]) + 1);
//再次遍历数组
for(int i = 0; i < array.length; i++)
//找到频率为1的两个数
if(mp.get(array[i]) == 1)
res.add(array[i]);
//整理次序
if(res.get(0) < res.get(1))
return new int[] {res.get(0), res.get(1)};
else
return new int[] {res.get(1), res.get(0)};
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK