1. 程式人生 > >462. Minimum Moves to Equal Array Elements II(python+cpp)

462. Minimum Moves to Equal Array Elements II(python+cpp)

題目:

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: 2
Explanation: Only two moves are needed (remember each move increments or 
decrements one element):
[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

解釋:
這系列的第一題:453. Minimum Moves to Equal Array Elements(python+cpp),其實給n-1個數字加1,效果等同於給那個未被選中的數字減1,所以題目轉換成將所有值都轉換為最小值所需要的步數。
這道題目是選擇一個元素+1或者選擇一個元素-1
 如果只能-1,則全部往最小值走
 如果只能+1,則全部往最大值走
 如果能+1也能-1,則全部往中間走
首先給陣列排序,那麼我們最終需要變成的相等的數字就是中間的數,如果陣列有奇數個,那麼就是最中間的那個數字;如果是偶數個,那麼就是中間兩個數的區間中的任意一個數字。
而兩端的數字變成中間的一個數字需要的步數實際上就是兩端數字的距離(設兩端是A

B,則需要走的步數=(B-C)+(C-A)==B-A),我們就兩對兩對的累加它們的差值就可以了。
~是取反的意思,但是~0==-1 ~1==-2
nums[~i] nums[i]表示取nums中對稱的元素。
python程式碼:

class Solution(object):
    def minMoves2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return sum([nums[~i]-nums[
i] for i in range(len(nums)/2)])

c++中如何取對稱元素。

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

總結:
按位取反運算子:對資料的每個二進位制位取反,即把1變為0,把0變為1 。~x 類似於 -x-1