- 921. Minimum Add to Make Parentheses Valid 使括号有效的最少添加
- 915. Partition Array into Disjoint Intervals 分割数组
- 932. Beautiful Array 漂亮数组
- 940. Distinct Subsequences II 不同的子序列 II
题目地址:https://leetcode.com/problems/sort-array-by-parity/description/
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
Youmay return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
对数组A按照偶数和奇数重新排序,使得偶数在前,奇数在后。可以返回任何一种满足这个条件的数组即可。
看到排序就写个排序就行了,比较的 key 是对 2 取余数之后的值。这样偶数取余得 0,排在前面,奇数取余得 1,排在后面。
Python 代码如下:
class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
return sorted(A, key = lambda x : x % 2)
1 2 3 4 5 6 7
C++代码如下:
bool cmp(int i, int j) {
return i % 2 < j % 2;
};
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
sort(nums.begin(), nums.end(), cmp);
return nums;
}
};
1 2 3 4 5 6 7 8 9 10
DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有
本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
这个测试行得通吗?: if (testInt/2).ofType(Integer){ //to-do if even } 我假设它会 iff 编译器在 ofType() 之前解析 testIn
我正在尝试更好地排列图像,而不仅仅是 1 列中的图像。示例见附件,每篇文章的图片可以在左右。 这是我的代码。HTML: Content 1
我有一个看起来像这样的定义: Title Entry Entry Entry Title Entry Title Entry Entry Title E
我是一名优秀的程序员,十分优秀!