leetcode442. Find All Duplicates in an Array
来源:互联网 发布:网络硬盘录像机 交换机 编辑:程序博客网 时间:2024/05/22 13:27
442. Find All Duplicates in an Array
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:Input:[4,3,2,7,8,2,3,1]Output:[2,3]
解法一
判断数组的中的某一项值是否已经发生变化。如num[i]=7, 对7-1=6,num[6]的位置发生变化,如果7只出现一次,则num[6]变化一次;如果7只出现两次,而num[6]已经发生了变化,则找到原来的值6+1.
public class Solution { public List<Integer> findDuplicates(int[] nums) { List<Integer> ret = new ArrayList<>(); if (nums == null || nums.length == 0) { return ret; } int len = nums.length; for (int i = 0; i < nums.length; i++) { int index = (nums[i] - 1) % len; if (nums[index] > len) { ret.add(index + 1); } else { nums[index] += len; } } return ret; }}
解法二
判断某一项是否为负数。
public class Solution { public List<Integer> findDuplicates(int[] nums) { List<Integer> ret = new ArrayList<>(); if (nums == null || nums.length == 0) { return ret; } for (int i = 0; i < nums.length; i++) { int index = Math.abs(nums[i]) - 1; if (nums[index] < 0) { ret.add(index + 1); } else { nums[index] *= -1; } } return ret; }}
0 0
- Leetcode442. Find All Duplicates in an Array
- leetcode442. Find All Duplicates in an Array
- leetcode442 Find All Duplicates in an Array
- Leetcode442. Find All Duplicates in an Array
- leetcode442 Find All Duplicates In An Array Java
- python--leetcode442. Find All Duplicates in an Array
- 25.leetCode442:Find All Duplicates in an Array
- LeetCode442. Find All Duplicates in an Array解题
- 442. Find All Duplicates in an Array
- [LeetCode]Find All Duplicates in an Array
- LeetCode Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- Leetcode Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- [Leetcode] Find All Duplicates in an Array
- 移动支付
- iOS Bundle (1)
- 从UDP的”连接性”说起–告知你不为人知的UDP
- Android进程保活的一般套路
- 神经网络基础介绍(一)
- leetcode442. Find All Duplicates in an Array
- 用Hexo+github Page搭建个人博客
- 将SD卡和USB中的文件软链接到/data/data/appname/XXX下
- [LintCode]Majority Number III
- iOS极速安装CocoaPods详细过程
- 蓝桥B组3题
- lintcode 165 合并两个排序链表
- 这 7 款开源思维导图工具真的很神奇
- 手机调试碰到的坑