941. Valid Mountain Array
Given an array A
of integers, return true
if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
- There exists some
i
with0 < i < A.length - 1
such that:A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]
Example 1:
Input: [2,1] Output: false
Example 2:
Input: [3,5,5] Output: false
Example 3:
Input: [0,3,2,1] Output: true
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。
让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:
A.length >= 3
在 0 < i < A.length - 1 条件下,存在 i 使得:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[B.length - 1]
思路:如果数组长度小于3,返回false;寻找数组最大值的位置,如果该位置等于0或者等于数组末尾,都返回false;接着看该最大位置的左右两侧是不是单调增和单调减。
class Solution:
def validMountainArray(self, A):
if len(A)<3:
return False
maxid=A.index(max(A))
if maxid==0 or maxid==len(A)-1:
return False
for i in range(0,maxid):
if A[i+1]<=A[i]:
return False
for i in range(maxid+1,len(A)):
if A[i]>=A[i-1]:
return False
return True
922. Sort Array By Parity II
Given an array A
of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i]
is odd, i
is odd; and whenever A[i]
is even, i
is even.
You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
思路:复制一个数组,直接进行奇偶判断,进行插入
class Solution:
def sortArrayByParityII(self, A):
odd=1
even=0
l=A.copy()
length=len(A)
for x in A:
if x%2==0:
l[even]=x
if even<length-2:
even+=2
else:
l[odd]=x
if odd<length-1:
odd+=2
return l