[LeetCode-JAVA] Next Permutation

來源:互聯網
上載者:User

標籤:

題目:

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

題意:找到下一個排列數

思路:主要就是根據經驗,要記住這個找排列數的規律

(1) 首先從後往前找到第一個下降的位置,記為i,如果沒有則證明是最後一個排序,下一個為原串的逆序

(2) 從i往後,找到比i對應的數值大的當中最小的對應的index(由於後面都是降序的,所以找到第一個小於等於i對應的數值的前一個即為所求),如果沒有則為length-1;

註: (例如 2,3,6,5,4,1  第一個降序的為3 比3大的當中 最小的為4)

(3) 交換nums[i] 和 nums[index] 

(4) 將i後面的逆序

代碼:

public class Solution {    public void nextPermutation(int[] nums) {        if(nums.length < 2)            return;        for(int i = nums.length - 2 ; i >= 0 ; i--) {            if(nums[i] < nums[i+1]) {               int index = nums.length - 1;               for(int j = i + 1 ; j < nums.length ; j++) { // 找到比nums[index]大的當中最小的                   if(nums[j] <= nums[i]){  //一定要有等號哦                       index = j - 1;                       break;                   }               }               int temp = nums[i];               nums[i] = nums[index];               nums[index] = temp;                              reverse(nums, i+1, nums.length-1);               return;            }        }                reverse(nums, 0, nums.length-1);        return;    }        public void reverse(int[] nums, int begin, int end) {        if(begin == end)            return;                while(begin < end) {            int temp = nums[begin];            nums[begin] = nums[end];            nums[end] = temp;            begin++;            end--;        }    } }

 

[LeetCode-JAVA] Next Permutation

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.