第一次周赛简单记录下。
来源:第 340 场周赛 - 力扣(LeetCode)
一、问题描述
* 6360等值距离和 显示英文描述
* 通过的用户数855
* 尝试过的用户数2022
* 用户总通过次数860
* 用户总提交次数3133
* 题目难度Medium
* 给你一个下标从 0 开始的整数数组 nums 。现有一个长度等于 nums.length 的数组 arr 。对于满足 nums[j] == nums[i] 且 j != i 的所有 j ,
* arr[i] 等于所有 |i - j| 之和。如果不存在这样的 j ,则令 arr[i] 等于 0 。返回数组 arr 。
* 示例 1: 输入:nums = [1,3,1,1,2] 输出:[5,0,3,4,0]
* 解释: i = 0 ,nums[0] == nums[2] 且 nums[0] == nums[3] 。因此,arr[0] = |0 - 2| + |0 - 3| = 5 。
* i = 1 ,arr[1] = 0 因为不存在值等于 3 的其他下标。
* i = 2 ,nums[2] == nums[0] 且 nums[2] == nums[3] 。因此,arr[2] = |2 - 0| + |2 - 3| = 3 。
* i = 3 ,nums[3] == nums[0] 且 nums[3] == nums[2] 。因此,arr[3] = |3 - 0| + |3 - 2| = 4 。
* i = 4 ,arr[4] = 0 因为不存在值等于 2 的其他下标。
* 示例 2: 输入:nums = [0,5,3] 输出:[0,0,0] 解释:因为 nums 中的元素互不相同,对于所有 i ,都有 arr[i] = 0 。
* 提示: 1 <= nums.length <= 105 0 <= nums[i] <= 109
二、题解:
思路1:
题解1-超时:
思路应该是正确的,但是超时了。
class Solution {
public long[] distance(int[] nums) {
HashMap<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Set<Integer> set = map.get(nums[i]);
if (set == null) {
set = new HashSet<>();
set.add(i);
map.put(nums[i], set);
} else {
set.add(i);
}
}
long[] myRes = new long[nums.length];
for (int i = 0; i < nums.length; i++) {
Set<Integer> set = map.get(nums[i]);
if (set.size() == 1) continue;
for (int j : set) myRes[i] += Math.abs(i - j);
}
return myRes;
}
}
个人测试:
@Test
public void testSolution(){
int[][] arr = {
{1,3,1,1,2},//5,0,3,4,0
{0,5,3},//0,0,0
// {},
};
for (int[] ints : arr) {
System.out.println(Arrays.toString(ints) + ", result is " + Arrays.toString(distance(ints)));
}
}
思路2:
这个题和之前做的一道题是差不多的,也就是前缀和以及后缀和。实际上就是这道题的稍微变型( 238除自身以外数组的乘积-hot100-Java_xin麒的博客-优快云博客,做过238这个题应该就可以采取238的思路做出来了。
题解2:
class Solution {
public long[] distance(int[] nums) {
long[] myRes = new long[nums.length];
HashMap<Integer, long[]> mapLeft = new HashMap<>();
HashMap<Integer, long[]> mapRight = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
long[] arrLeft = mapLeft.get(nums[i]);
if (arrLeft == null){
arrLeft = new long[2];
arrLeft[0] = i;
arrLeft[1] = 1;
mapLeft.put(nums[i],arrLeft);
}else {
myRes[i] += i * arrLeft[1] - arrLeft[0];
arrLeft[0] += i;
arrLeft[1]++;
}
long[] arrRight = mapRight.get(nums[nums.length - 1 - i]);
if (arrRight == null){
arrRight = new long[2];
arrRight[0] = nums.length - 1 - i;
arrRight[1] = 1;
mapRight.put(nums[nums.length - 1 - i],arrRight);
}else {
myRes[nums.length - 1 - i] += arrRight[0] - (nums.length - 1 - i) * arrRight[1];
arrRight[0] += nums.length - 1 - i;
arrRight[1]++;
}
}
return myRes;
}
}