<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          ?LeetCode刷題實戰(zhàn)462:最少移動次數(shù)使數(shù)組元素相等 II

          共 1088字,需瀏覽 3分鐘

           ·

          2021-12-14 01:13

          算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !

          今天和大家聊的問題叫做?最少移動次數(shù)使數(shù)組元素相等 II,我們先來看題面:
          https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements-ii/

          Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

          In one move, you can increment or decrement an element of the array by 1.

          Test cases are designed so that the answer will fit in a 32-bit integer.

          給定一個非空整數(shù)數(shù)組,找到使所有數(shù)組元素相等所需的最小移動數(shù),其中每次移動可將選定的一個元素加1或減1。 您可以假設(shè)數(shù)組的長度最多為10000。

          示例? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


          輸入:
          [1,2,3]

          輸出:
          2

          說明:
          只有兩個動作是必要的(記得每一步僅可使其中一個元素加1或減1):
          [1,2,3] => [2,2,3] => [2,2,2]


          解題


          class?Solution?{
          public:
          ????int?minMoves2(vector<int>& nums)?{
          ????????sort(nums.begin(),nums.end());
          ????????int?i = 0,j = nums.size() - 1,ans = 0;
          ????????while(i < j) ans += nums[j--] - nums[i++];
          ????????return?ans;
          ????}
          };

          好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動力 。

          上期推文:

          LeetCode1-460題匯總,希望對你有點幫助!

          LeetCode刷題實戰(zhàn)461:漢明距離


          瀏覽 45
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美91成人网 | 99九九99九九九99九他書對 | www.三级在线 | 亚洲黄片黄片 | 久久综合8 |