Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Natural Greedy. Sort the array and pick the medium as target.

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int n = nums.size();
        if(n == 1) return 0;
        
        sort(nums.begin(), nums.end());
        
        int mid = nums[n/2];
        int ret = 0;
        for(auto v : nums) ret += abs(v - mid);
        return ret;
    }
};

 

posted on 2017-01-14 14:40  Tonix  阅读(99)  评论(0编辑  收藏  举报