当前位置:网站首页>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)。
边栏推荐
- CSDN's one-stop cloud service is open for internal testing, and new and old users are sincerely invited to grab the fresh
- 云原生到底是什么?它会是未来发展的趋势吗?
- SQL server2014 failed to delete the database, with an error offset of 0x0000
- uniapp微信小程序组件按需引入
- Graduation summary of actual combat camp
- 好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与!
- C one line code calculates the MD5 value of the file - codeplus series
- MySQL common commands
- PO模式深入封装
- What a high commission! The new programmer's partner plan is coming. Everyone can participate!
猜你喜欢
The programmer was beaten.
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;
C [byte array] and [hexadecimal string] mutual conversion - codeplus series
bash: ln: command not found
Live broadcast management project
机器学习之线性回归详解
Common penetration tools -goby
C one line code calculates the MD5 value of the file - codeplus series
【论文阅读】Trajectory-guided Control Prediction for End-to-end Autonomous Driving: A Simple yet Strong Ba
直播管理项目
随机推荐
leetcode:111. 二叉树的最小深度
京东与腾讯续签三年战略合作协议;起薪涨至26万元!韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条...
哪个券商公司炒股开户佣金低又安全又可靠
我喜欢两个男人。。。
这样理解mmap,挺有意思!
亿学学堂帮个人开的证券账户安全吗?是不是有套路
客户端如何请求数据库?
大佬们 有没有搞过sink分流写入clickhouse 或者其他数据库的操作。
About widthstep of images in opencv
SQL statement modify field type "suggestions collection"
关于OpenCV中图像的widthStep
[dark horse morning post] Yu Minhong said he never looked at the stock price of New Oriental; Hengchi 5 will start pre-sale in July; Naixue virtual stock or suspected of illegal fund-raising; From Jul
HMS core audio editing service 3D audio technology helps create an immersive auditory feast
全球基金和资管的股票建仓率达到15年内新低
问下群里的各位,有使用flink oracle cdc的logminer方案,在生产上稳定运行的实际
程序员都想去国企?技术落后薪资低,躺平几年出来都找不到工作...
It is interesting to understand MMAP in this way!
PO模式深入封装
MySQL interception_ MySQL method for intercepting strings [easy to understand]
零基础入行软件测试必看,10年测试老鸟的良心建议(共15条)