From 1521e4016537243bd2a6d5898f2099e53f588d42 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 20:00:16 +0800 Subject: [PATCH] =?UTF-8?q?31.=E4=B8=8B=E4=B8=80=E4=B8=AA=E6=8E=92?= =?UTF-8?q?=E5=88=97=20=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0031.下一个排列.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index fbe31eb3..53e6644d 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -99,6 +99,24 @@ public: ## Java ```java +class Solution { + public void nextPermutation(int[] nums) { + for (int i = nums.length - 1; i >= 0; i--) { + for (int j = nums.length - 1; j > i; j--) { + if (nums[j] > nums[i]) { + // 交换 + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + // [i + 1, nums.length) 内元素升序排序 + Arrays.sort(nums, i + 1, nums.length); + return; + } + } + } + Arrays.sort(nums); // 不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 + } +} ``` ## Python