leetcode 数组Ⅰ(21-02-17)
两数之和(简单)
public class TwoNumSum {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
//巧妙的运用HashMap
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{i, map.get(target - nums[i])};
} else {
map.put(nums[i], i);
}
}
return null;
}
}
最大子序和(简单)
public class MaxSubArray {
public int maxSubArray(int[] nums) {
int sum = 0;
int max = nums[0];
for (int i = 0; i < nums.length ; i ++){
if(sum < 0){
sum = 0;
}
sum += nums[i];
if(sum > max){
max = sum;
}
}
return max;
}
//优化
public int maxSubArray2(int[] nums) {
int sum = 0;
int max = nums[0];
for (int i = 1; i < nums.length ; i ++){ //从位置2开始
int cur = Math.max(nums[i], sum + nums[i]); //加上了nums[i]之后,当前位置的最优值
max = Math.max(max, cur);
sum = cur; //把累积和换成当前位置的最优值
}
return max;
}
}
使数组唯一的最小增量 (中等)
//空间换时间
int minIncrementForUniqueA(int[] A) {
int[] n = new int[50000];
Arrays.fill(n,0);
int len = A.length;
for (int i = 0; i < len; i++) {
n[A[i]]++;
}
int move = 0;
for (int i = 0; i < 50000; i++) {
if (n[i] <= 1) {
continue;
}
move += n[i] - 1; //如果一个数字出现次数大于1,则只保留一个,其余的该数字都全部加1先 ,move等于该数字出现次数减1
n[i + 1] += n[i] - 1; //则 i + 1 的次数加上新move的个数
n[i] = 1; //则 i 的次数则只剩1
}
return move;
}
public int minIncrementForUnique(int[] A) {
Arrays.sort(A); //默认是升序排
int move = 0;
for (int i = 1; i < A.length; i++) {
if(A[i] <= A[i-1]){ //如果当前元素小于或等于前一个元素,则变为前一个元素+1
int change = A[i-1] - A[i] + 1;
A[i] = A[i-1] + 1;
move += change;
}
}
return move;
}
//错误 超出时间限制
public int minIncrementForUnique2(int[] A) {
int move = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < A.length; i++) {
if (map.containsKey(A[i])) {
do {
A[i]++;
move++;
} while (map.containsKey(A[i]));
map.put(A[i], i);
} else {
map.put(A[i], i);
}
}
return move;
}
附上leetcode数组标签题库按频率排序图完成度