Java for Leetcode 031 Next permutation

Source: Internet
Author: User

Next permutation

Total Accepted: 33595 submissions: 134095

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

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

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

Problem Solving Ideas:

The problem is not difficult, the key is to understand the meaning of the topic: if the nums as a number, that is, the return of the smallest number than the original number (if not (the original number is in descending order) is returned to order.

Not very difficult, Java implementation is as follows:

static public void Nextpermutation (int[] nums) {int index = nums.length-1;while (index >= 1) {if (Nums[index] > Nu Ms[index-1]) {int swapnum=nums[index-1],swapindex = Index+1;while (swapindex <= nums.length-1&& swapNum < ; Nums[swapindex]) Swapindex++;nums[index-1]=nums[swapindex-1];nums[swapindex-1]=swapnum;reverse (Nums,index); return;} index--;} Reverse (nums,0);} static void reverse (int[] Nums,int swapindex) {int[] swap=new int[nums.length-swapindex];for (int i=0;i<swap.length; i++) swap[i]=nums[nums.length-1-i];for (int i=0;i<swap.length;i++) nums[swapindex+i]=swap[i];}

Java for Leetcode 031 Next permutation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.