775. Global and Local Inversions
We have some permutation A of [0, 1, …, N - 1], where N is the length of A.
The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].
The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].
Return true if and only if the number of global inversions is equal to the number of local inversions.
Example 1:
Input: A = [1,0,2]
Output: true
Explanation: There is 1 global inversion, and 1 local inversion.
All local inversions are global inversions.
If the number of global inversions is equal to the number of local inversions,
it means that all global inversions in permutations are local inversions.
It also means that we can not find A[i] > A[j] with i+2<=j.
In other words, max(A[i]) < A[i+2]
In this first solution, I traverse A and keep the current biggest number cmax.
Then I check the condition cmax < A[i+2]
class Solution(object):
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if len(A)<3:
return True
mx=-sys.maxint
#if subarray is global inversioin among 3 continuous number, then it will be false
for i in range(len(A)-2):
mx=max(mx,A[i])
if A[i+2]<mx:
return False
return True
280. Wiggle Sort
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]…
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
# O(nlogn)
def wiggleSort(nums):
nums.sort()
i=2
while i<len(nums):
swap(nums[i],nums[i-1])
i+=2
# O(n)
def wiggleSort(nums):
for i in range(1,len(nums)):
if i%2 and nums[i]<nums[i-1] or (i%2==0 and nums[i]>nums[i-1])
swap(nums[i],nums[i-1])
324. Wiggle Sort II
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]…
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
nums.sort()
if len(nums)<=2:
return
temp=nums[:]
k=len(nums)-1
j=(len(nums)-1)//2
#j=0 # cannot tranverse from the beginning, will fail on the [1,3,2,2,3,1] case==>
for i in range(len(nums)):
#print j,k
if i%2:
nums[i]=temp[k]
k-=1
else:
nums[i]=temp[j]
j-=1