Created
April 21, 2021 04:02
-
-
Save rohanjai777/786230c5f492e9e2a72affafa6f20b1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int[] nextPermutation(int[] arr) { | |
if(arr.length <= 1){ | |
return arr; | |
} | |
int i = arr.length-1; | |
while(i>0 && arr[i-1] >= arr[i]){ | |
i--; | |
} | |
if(i == 0){ | |
reverse(arr,i); | |
return arr; | |
} | |
int j = i+1; | |
while(j<arr.length && arr[j] > arr[i-1]){ | |
j++; | |
} | |
swap(arr,i-1,j-1); | |
reverse(arr,i); | |
return arr; | |
} | |
public void reverse(int[] arr, int i){ | |
int j = arr.length-1; | |
while(i<j){ | |
swap(arr,i,j); | |
i++; | |
j--; | |
} | |
} | |
public void swap(int arr[], int i, int j){ | |
int temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment