提交 1c871a9e 编写于 作者: 朱力

【645. 错误的集合】【Java】

上级 8b8f4135
# 如何寻找缺失和重复的元素
# 如何寻找缺失和重复的元素
<p align='center'>
......@@ -139,4 +139,30 @@ vector<int> findErrorNums(vector<int>& nums) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
[zhuli](https://github.com/1097452462 "zhuli")提供的Java代码:
```java
class Solution {
public int[] findErrorNums(int[] nums) {
int n = nums.length;
int dup = -1;
for (int i = 0; i < n; i++) {
// 元素是从 1 开始的
int index = Math.abs(nums[i]) - 1;
// nums[index] 小于 0 则说明重复访问
if (nums[index] < 0)
dup = Math.abs(nums[i]);
else
nums[index] *= -1;
}
int missing = -1;
for (int i = 0; i < n; i++)
// nums[i] 大于 0 则说明没有访问
if (nums[i] > 0)
// 将索引转换成元素
missing = i + 1;
return new int[]{dup, missing};
}
}
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册