LeetCode 462. Minimum Moves to Equal Array Elements II

来源:互联网 发布:南京大学 人工智能 编辑:程序博客网 时间:2024/06/05 12:45

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array's length is at most 10,000.

Example:

Input:[1,2,3]Output:2Explanation:Only two moves are needed (remember each move increments or decrements one element):[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

Subscribe to see which companies asked this question

class Solution {public:    int minMoves2(vector<int>& nums) {        int result = 0;        int n = nums.size();        int median = medianVal(nums);        for (int i = 0; i < n; ++i) {            result += abs(nums[i] - median);        }        return result;    }private:    inline void swap(int& a, int& b) {        int temp = a;        a = b;        b = temp;    }    int medianVal(vector<int>& nums) {        int n = nums.size();        int left = 0, right = n - 1;        int mid = n / 2;        while (true) {            int k = left;            int temp = rand() % (right - left + 1) + left;            swap(nums[right], nums[temp]);            for (int i = left; i < right; ++i) {                if (nums[i] < nums[right]) {                    swap(nums[i], nums[k++]);                }            }            swap(nums[right], nums[k]);            if (k == mid) {                return nums[k];            }            else if (k < mid) {                left = k + 1;            }            else {                right = k - 1;            }        }    }};


0 0
原创粉丝点击