LeetCode brush questions - the next arrangement

next permutation

topic

The next permutation of an array of integers refers to the next lexicographically greater permutation of its integers. More formally, if all permutations of an array are arranged in a container according to their lexicographical order, then the next permutation of the array is the one that comes after it in this ordered container. If no next larger permutation exists, the array must be rearranged into the lexicographically smallest permutation (that is, its elements are in ascending order).
Link

train of thought

Traverse the array from right to left, find the first position where the current bit is smaller than the last bit, record it as left, if left is the initial value, it means that the array is completely in descending order, and directly reverse the entire array; otherwise, go from right to left Traverse, find the first number greater than nums[left], exchange it with nums[left], reverse the part of the array from left+1 to the end, which is the next arrangement

class solution {
    
    
	public void nextPermutation(int[] nums) {
    
    
		int len = nums.length;
		int left = -1;
		// left为比后一位更小的数的索引
		for (int i = len - 2; i >= 0; i--) {
    
    
			if (nums[i] < nums[i + 1]) {
    
    
				left = i;
				break;
			}
		}

		if (left == -1) {
    
    
			reverse(nums, 0, len - 1);
		} else {
    
    
			int right = -1;
      		// right为从右往左比nums[left]大的第一个数的索引
			for (int j = len - 1; j > left; j--) {
    
    
				if (nums[j] > nums[left]) {
    
    
					right = j;
					break;
				}
			}
			int tmp = nums[left];
			nums[left] = nums[right];
			nums[right] = tmp;
			reverse(nums, left + 1, len - 1);
		}
	}

  	// 将数组在L~R范围内反转
	public void reverse(int[] nums, int L, int R) {
    
    
		while (L < R) {
    
    
			int tmp = nums[L];
			nums[L] = nums[R];
			nums[R] = tmp;
			L++;
			R--;
		}
	}
}

Guess you like

Origin blog.csdn.net/wzc3614/article/details/129477079