leetcode刷题——day3
645. 错误的集合
class Solution {
public int[] findErrorNums(int[] nums) {
int[] err = new int[2];
int n = nums.length;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int cur : nums) {
map.put(cur, map.getOrDefault(cur, 0) + 1);
}
for(int i = 1; i <= n; i++) {
int count = map.getOrDefault(i, 0);
if(count == 2) err[0] = i;
if(count == 0) err[1] = i;
}
return err;
}
}
697. 数组的度
class Solution {
public int findShortestSubArray(int[] nums) {
int n = nums.length;
Map<Integer, int[]> map = new HashMap<Integer, int[]>();
for(int i = 0; i < n; i++) {
if(map.containsKey(nums[i])) {
map.get(nums[i])[0]++;
map.get(nums[i])[2] = i;
} else {
map.put(nums[i], new int[]{1, i, i});
}
}
int minLen = n;
int maxDegree = 0;
for(Map.Entry<Integer,int[]> entry : map.entrySet()) {
int[] arr = entry.getValue();
if(arr[0] > maxDegree) {
maxDegree = arr[0];
minLen = arr[2] - arr[1] + 1;
} else if(arr[0] == maxDegree) {
minLen = Math.min(minLen, arr[2] - arr[1] + 1);
}
}
return minLen;
}
}
作者:lykxbg —— 来一块小饼干
出处:http://www.cnblogs.com/lykxbg/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。