Leetcode——Array 2
来源:互联网 发布:淘宝买鹿王羊绒衫 编辑:程序博客网 时间:2024/06/06 22:08
Find All Numbers Disappeared in an Array
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:[4,3,2,7,8,2,3,1]Output:[5,6]
思路:
个人做该题的第一思路是排序,然后遍历查找nums[i] - nums[i - 1] > 1
的间隔,但是算法复杂度是O(nlog2n)的。而别人的解答主要是直接在原来的数组上进行修改,一种是将nums[Math.abs(nums[i])- 1]
取反,另一种是将nums[nums[i] - 1] += n
;之后在进行一次遍历,确定缺少的数字。
代码实现:
public class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { ArrayList<Integer> list = new ArrayList<Integer> (); for(int i = 0; i < nums.length; i++){ int value = Math.abs(nums[i])-1; if(nums[value] > 0) nums[value] = -nums[value]; // remember to add if, otherwise -(-a) may occur } for(int i = 0; i < nums.length; i++){ if(nums[i] >= 0) list.add(i+1); } return list; }}
类似的还有:442. Find All Duplicates in an Array
0 0
- Leetcode——Array 2
- LeetCode——Rotate Array
- Leetcode——Array 3
- 【leetcode】Array——Rotate Array(189)
- 刷leetcode小记2——array(122)
- LeetCode——Merge Sorted Array
- LeetCode——Merge Sorted Array
- LeetCode——Merge Sorted Array
- Merge Sorted Array —— Leetcode
- LeetCode——Merge Sorted Array
- LeetCode题解——Merge Sorted Array
- leetcode 088 —— Merge Sorted Array
- LeetCode题解——Rotate Array
- leetcode 88 ——Merge Sorted Array
- 【leetcode】Array——word search(79)
- 【leetcode】Array——Triangle(120)
- 【leetcode】Array——Subsets(78)
- 【leetcode】Array——SubsetsII(90)
- php中类之间继承关系
- c++实现解析文件路径
- 动态规划总结
- rootViewController获取真的如你想的那么简单吗
- Tomcat 8005、8009和8080端口
- Leetcode——Array 2
- SpringMVC学习系列(8) 之 国际化
- C 编译错误 warning : no newline at end of file 解决
- 第五章 5-3 画刷
- Coordinationlayout解析之二
- vb.net 教程 3-2 窗体编程之窗体 2
- OkHttp Wiki翻译(三)连接
- Java 集合转换(数组、List、Set、Map相互转换)
- ECMAScript 6 入门笔记(六)Class