GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/031_Next_Permutation.py at master · naironics/leetcode

Expand file tree

/

031_Next_Permutation.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
54 lines (48 loc) · 1.67 KB
/

031_Next_Permutation.py

Copy path

File metadata and controls

54 lines (48 loc) · 1.67 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
ls = len(nums)
if ls <= 1:
return
pair = []
for i in range(ls):
for j in range(i + 1, ls):
# append ascending order pair
if nums[i] < nums[j]:
pair.append([i,j])
pos = 0
if len(pair) > 0:
self.swap(nums, pair[-1][0], pair[-1][1])
pos = pair[-1][0] + 1
# sort from pos
for i in range(pos, ls):
for j in range(i + 1, ls):
if nums[i] > nums[j]:
self.swap(nums, i, j)
def swap(self, nums, index1, index2):
if index1 == index2:
return
nums[index1], nums[index2] = nums[index2], nums[index1]
# def nextPermutation(self, nums):
# # https://leetcode.com/discuss/86630/fast-and-easy-python-solution-beaten-79%25
# pos = -1
# ls = len(nums)
# for i in range(ls - 1, 0, -1):
# if nums[i] > nums[i - 1]:
# pos = i - 1
# break
# if pos == -1:
# self.re_order(nums, 0, ls - 1)
# return
# for i in range(ls - 1, -1, -1):
# if nums[pos] < nums[i]:
# nums[pos], nums[i] = nums[i], nums[pos]
# self.re_order(nums, pos + 1, ls - 1)
# break
#
# def re_order(self, a, start, end):
# for i in range(0, (end - start + 1) // 2):
# a[start + i], a[end - i] = a[end - i], a[start + i]
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.