448. Find All Numbers Disappeared in an Array
原题链接:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/
我的解答:
import java.util.ArrayList;
import java.util.List;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.findDisappearedNumbers(new int[]{4, 3, 2, 7, 8, 2, 3, 1}));
}
// 哈哈哈😆,这道题目完全自己实现解答的,时间复杂度和空间复杂度基本上也都题目的要求,这些天刷算法题总算有点效果了。。。
// 哎😔,又自欺欺人了,仔细想了一下,这道题目的思路好像之前《剑指Offer》这本书上看到的某道题的解法。。。
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>(nums.length >> 1);
for (int i = 0; i < nums.length; i++) {
while (nums[i] != (i + 1) && nums[nums[i] - 1] != nums[i]) {
int temp = nums[i];
nums[i] = nums[nums[i] - 1];
nums[temp - 1] = temp;
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != (i + 1)) {
res.add(i + 1);
}
}
return res;
}
}