Leetcode 448(Java)
来源:互联网 发布:云安全软件下载 编辑:程序博客网 时间:2024/06/01 17:59
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]
出现过的元素以其为下标获取数组中的值并取反,在对应元素大于0的情况下我们才取反,这样没有出现过的元素为下标的元素依然为正,可以写出AC码:(注意,元素范围为1~n,而下标范围为0~n-1)
public class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> result = new ArrayList<Integer>(); int index = 0; for(int i=0;i<nums.length;i++){ index = Math.abs(nums[i])-1; if(nums[index]>0){ nums[index]=-nums[index]; } } for(int j=0;j<nums.length;j++){ if(nums[j]>0){ result.add(j+1); } } return result; }}
0 0
- Leetcode 448(Java)
- Leetcode(java)
- leetcode java
- [LeetCode]Next Permutation java leetcode
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- [Leetcode] ZigZag Conversion (Java)
- [Leetcode] Reverse Integer (Java)
- [Leetcode] Palindrome Number (Java)
- [Leetcode] Valid Parentheses (Java)
- [Leetcode] Generate Parentheses (Java)
- [Leetcode] Remove Element (Java)
- [Leetcode] Implement strStr() (Java)
- [Leetcode] Next Permutation (Java)
- [Leetcode] Valid Sudoku (Java)
- [Leetcode] Sudoku Solver (Java)
- [Leetcode] Combination Sum (Java)
- [Leetcode] Multiply Strings (Java)
- 借助postman实现模拟登陆
- JSP页面报javax.servlet.jsp.PageContext cannot be resolved to a type 错误
- Linux基本命令
- mysql行转列、列转行
- 设计模式之建造者模式
- Leetcode 448(Java)
- redis cluster 添加 删除 重分配 节点
- 综合用户特征及专家信任的协作过滤推荐算法
- 如何将服务器传来的字符串转成HTML显示在前端页面
- rman report obsolete的问题
- Android Things专题2 硬件介绍
- 阻塞模式和非阻塞模式
- java中 final 与 static
- 在一台机器上部署多个Redis实例