leetcode刷題記錄Array篇(31~Next Permutation)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
##31.Next Permutation

題目: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.

翻譯:實現下一個排列,將數字重新排列成數位下一個更大排列。如果這種安排是不可能的,它必須將其重新排列為儘可能低的順序(即以升序排序)。替換必須在原位置,不要分配額外的記憶體。

思路:這題的題意比較隱晦啊,網上找了別人的例子才明白題目的意思。。。。,知道題目的意思後,解題簡單了很多。題意:就是把數組每個元素組合起來成為一個數字,比如[1,3,1,3,1],則為13131,然後用數組中的元素重新排列,得到比13131大一點的數,即13311,答案就是它.

實現過程:
1.倒序遍曆數組,如果nums[i-1]<nums[i],則i-1該位置需要調換值,我們設index=i-12.然後再次倒序遍曆,如果找到nums[i]>nums[index],調換兩個數字,並且把index下標後的數字升序排列,得到答案。
3.題目還要求沒有比原始值大的下一個排列,則需要把該原始序列升序排列,即3,2,1,沒有比他更大的數,則需要返回1,2,3

下面是代碼實現:

golang代碼:

    package main  import (      "fmt"  )  func main() {      nums := []int{1, 2}      nextPermutation(nums)      fmt.Println(nums)  }  func nextPermutation(nums []int) {    arrLen := len(nums)    if arrLen < 2 {        return    }    index := -1    for i := arrLen - 1; i > 0; i-- {        if nums[i-1] < nums[i] {            index = i - 1            break        }    }    if index == -1 {        reserve(nums)        return    }    for i := arrLen - 1; i > 0; i-- {        if nums[i] > nums[index] {            nums[i], nums[index] = nums[index], nums[i]            reserve(nums[index+1:])            break        }    }    return  }  func reserve(nums []int) {      for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {        nums[i], nums[j] = nums[j], nums[i]    }    return  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.