关于一个数组存储元素与下标存在关系中出现几种情况的算法解答
1.448. Find All Numbers Disappeared in an Array (https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)
题意:数组长度为n 里面存储元素为1到n 但部分元素重复 要求找出缺少的元素
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
解题关键为:利用下标与数组元素关系相等,先使用第一个for循环使数组中出现的元素的下标处的值统一加上n,
在利用第二个for循环判断数组中元素<n的则为没出现的(小于n的原因是第一个for循环为改变改值)
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < nums.length; i ++) nums[(nums[i]-1) % n] += n;
for (int i = 0; i < nums.length; i ++) if (nums[i] <= n) res.add(i+1);
//为什么是i+1 因为未修改的元素的数字就是那个下标+1 数字与下标加1一一对应 第一个for只是为了证明那个元 素被修改了
return res;
}
}
2. 287. Find the Duplicate Number
题意:数组长度为n,里面存储元素为1到n-1 有一个元素重复 找出重复元素
Input: [1,3,4,2,2]
Output: 2
Input: [3,1,3,4,2]
Output: 3
public class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length < 2) return 0;
int fast = nums[nums[0]];
int slow = nums[0];
while (fast != slow) {
fast = nums[nums[fast]];
slow = nums[slow];
}
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
}
3. 217. Contains Duplicate(https://leetcode.com/problems/contains-duplicate/)
题意:有重复元素返回true 没有则返回false
Input: [1,2,3,1]
Output: true
Input: [1,2,3,4]
Output: false
由于只需要返回true与false所以代码比较简单
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i : nums)
if(!set.add(i))// if there is same
return true;
return false;
}
}
4. 268. Missing Number(https://leetcode.com/problems/missing-number/)
题意:数组中无重复元素,数组长度为n 则元素为0到n 但缺少了部分元素 最后输出缺少的数字
Input: [3,0,1]
Output: 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
解题关键在于异或的运用 a^a^b =b xor的初值设置为nums.length也是很值得思考的 最终还是在利用数组元素与数组下标的关系来解题
数组元素为 3 0 1
数组下标为 0 1 2 3 (元素与下标异或)由于在for循环中i并没有取到nums.length也就是3 所以xor初值要设置为3
class Solution {
public int missingNumber(int[] nums) {
int xor = nums.length; //等于nums.length的原因是 异或之后刚好差这个元素
//因为i在for循环中只能到nums.length-1
for (int i = 0; i < nums.length; i++) {
xor = xor ^ i ^ nums[i];
}
return xor ;
}
}