Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def nextGreaterElement(self, num: int) -> int:
- arr=list(str(num))
- n=len(arr)
- i=n-2#3462431
- #Find peak point at which decreasing order breaks from right to left
- while i>=0 and arr[i]>=arr[i+1]:
- i-=1
- #If there is no peak return -1 [3462][431]
- if i==-1:
- return -1
- else:
- #Now find next immediate greater number while traversing from n-1 to peak point.
- #If you found swap and break[3463][421]
- #Now Reverse the array from peak point to last elementv[3463][124]------>ans
- for j in range(n-1,i,-1):
- if arr[i]<arr[j]:
- arr[i],arr[j]=arr[j],arr[i]
- break
- arr[i+1:]=arr[i+1:][::-1]
- t=int(''.join(arr))
- return t if t<(1<<31) else -1
- class Solution:
- def nextPermutation(self, a: List[int]) -> None:
- def swap(x,y,a):
- a[x],a[y]=a[y],a[x]
- n=len(a)
- i=n-1
- while i>=1:
- if a[i]>a[i-1]:
- for j in range(i,n):
- if a[j]>a[i-1]:
- next_swap=j
- else:
- break
- swap(next_swap,i-1,a)
- a[i:]=sorted(a[i:])
- break
- else:i=i-1
- if i==0:
- a.reverse()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement