Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-05-19 #242

Open Zheaoli opened 2 years ago

Zheaoli commented 2 years ago

2022-05-19

johnson329 commented 2 years ago

image wechatid:johnson

SaraadKun commented 2 years ago

462. 最少移动次数使数组元素相等 II

image

class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        int ans = 0;
        for (int i = 0; i < n/2; i++) {
            ans += nums[n - i - 1] - nums[i];
        }
        return ans;
    }
}

WeChat:Saraad

dreamhunter2333 commented 2 years ago
package main

import (
    "fmt"
    "sort"
)

/*
 * @lc app=leetcode.cn id=462 lang=golang
 *
 * [462] 最少移动次数使数组元素相等 II
 */

// @lc code=start
func minMoves2(nums []int) int {
    sort.Ints(nums)
    target := nums[len(nums)/2]
    res := 0
    for _, num := range nums {
        res += Abs(target - num)
    }
    return res
}

func Abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

// @lc code=end
func main() {
    fmt.Println(minMoves2([]int{1, 2, 3}))
    fmt.Println(minMoves2([]int{1, 10, 2, 9}))
}

微信id: 而我撑伞 来自 vscode 插件