当前位置:网站首页>442. 数组中重复的数据
442. 数组中重复的数据
2022-07-01 10:08:00 【hequnwang10】
一、题目描述
给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。
你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。
示例 1:
输入:nums = [4,3,2,7,8,2,3,1]
输出:[2,3]
示例 2:
输入:nums = [1,1,2]
输出:[1]
示例 3:
输入:nums = [1]
输出:[]
二、解题
一次遍历
正负号判断法,出现过的数字就数字取反,然后判断是否取反过。
class Solution {
public List<Integer> findDuplicates(int[] nums) {
//这题需要使用一次遍历 然后使用额外空间的算法
int length = nums.length;
List<Integer> res = new ArrayList<>();
for(int i = 0;i<length;i++){
int num = Math.abs(nums[i]);
if(nums[num-1] > 0){
nums[num-1] = -nums[num-1];
}else{
res.add(num);
}
}
return res;
}
}
时间复杂度:O(n)
空间复杂度:O(1)。
边栏推荐
- Centos 配置discuz 提示请检查 mysql 模块是否正确加载
- Configure load balancing
- This is the best flash popular science article I have ever seen!
- Project procurement management
- Sd-wan notes
- In the new database era, don't just learn Oracle and MySQL
- 好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与!
- 谁还在买“三只松鼠”们
- Flinkv1.13 implementation of financial anti fraud cases
- Finally, someone made it clear what DRAM and NAND flash are
猜你喜欢

Some tools used in embedded development

Initial experience of Flink, a mainstream real-time stream processing computing framework

JD and Tencent renewed the three-year strategic cooperation agreement; The starting salary rose to 260000 yuan! Samsung sk of South Korea competes for salary increase to retain semiconductor talents;

渗透常用工具-Goby

微信表情符号写入判决书,你发的OK、炸弹都可能成为“呈堂证供”

Precautions for lvgl v8.2 string display on keil MDK (take little bear pie as an example)

CSDN's one-stop cloud service is open for internal testing, and new and old users are sincerely invited to grab the fresh

Hardware midrange project

It is interesting to understand MMAP in this way!

12.Gateway新一代网关
随机推荐
SSH服务器拒绝密码,再试一次;PermitRootLogin yes无效问题
SQL statement modify field type "suggestions collection"
4hutool实战:DateUtil-格式化时间[通俗易懂]
Who has the vision to cross the cycle?
[fxcg] large scale job hopping may be one of the driving forces behind the soaring inflation in the United States
How did the data center change from "Britney Spears" to "Mrs. cow"?
超标量处理器设计 姚永斌 第4章 分支预测 --4.1 小节摘录
预制菜迎来“黄金时代”,谁能领跑下一个万亿市场
Button button clear border
Raspberry pie 4B system construction (ultra detailed version)
What if the win11 account is locked and unable to log in? Win11 account is locked and unable to log in
mysql cdc能把能把op字段拿出来吗
Wechat emoticons are written into the judgment, and the OK and bomb you send may become "testimony in court"
全球基金和资管的股票建仓率达到15年内新低
CSDN一站式云服务开放内测,诚邀新老用户来抢鲜
What is cloud primordial? Will it be the trend of future development?
Floyd repeat
SQL SERVER2014删除数据库失败,报错偏移量0x0000...
The "China Mobile Chain" state secret engine was officially launched on BSN
架构实战营 毕业总结