3446. 整数奇偶排序

3446.整数奇偶排序

⭐️难度:简单

⭐️类型:排序

📖题目:题目链接

🌟思路:考察sort函数自定义排序规则

因为自定义函数的两个参数 lhs 和 rhs 不发生交换时,才返回真

所以要找出 不交换的 情况:

📚题解:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<vector>  // vector不需要.h
#include<list>
#include<set>  // // 可以用 set 和 multiset
#include<unordered_set> // 可以用 unordered_set 和 unordered_multimap
#include<map>  // 可以用 map 和 multimap
#include<unordered_map> // 可以用 unordered_map 和 unordered_multimap
#include<algorithm>

using namespace std;

bool compare(int lhs, int rhs) {
    if (lhs % 2 == 1 && rhs % 2 == 0) { // 左奇右偶,不交换
        return true;
    }
    else if (lhs % 2 == 1 && rhs % 2 == 1 && lhs > rhs) { // 左奇右奇 且 左>右,不交换
        return true;
    }
    else if (lhs % 2 == 0 && rhs % 2 == 0 && lhs < rhs) { // 左偶右偶 且 左<右,不交换
        return true;
    }
    else { // 其余情况全部交换
        return false; 
    }
}

int main() {
    int arr[10];
    for (int i = 0;i < 10;i++) {
        scanf("%d", &arr[i]);  // arr + i
    }
    sort(arr, arr + 10, compare);
    for (int i = 0;i < 10;i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
相关推荐
闻缺陷则喜何志丹15 天前
【前后缀分解 排序】B4274 [蓝桥杯青少年组省赛 2023] 数字游戏|普及+
c++·蓝桥杯·排序·洛谷·前后缀分解
知无不研18 天前
冒泡排序算法
算法·冒泡排序·排序
Tisfy18 天前
LeetCode 3010.将数组分成最小总代价的子数组 I:排序 OR 维护最小次小
算法·leetcode·题解·排序·最小次小值
码农幻想梦19 天前
PKUKY109 小白鼠排队
排序
西京刀客20 天前
MySQL字符集排序规则冲突问题(utf8mb4_unicode_ci和utf8mb4_0900_ai_ci )
mysql·排序·utf8mb4
GHZhao_GIS_RS20 天前
python中的sort和sorted用法汇总
python·排序·列表
码农幻想梦21 天前
3376. 成绩排序2
排序
Tisfy23 天前
LeetCode 3651.带传送的最小路径成本:动态规划
算法·leetcode·动态规划·题解·排序
2401_841495641 个月前
【Python高级编程】单词统计与查找分析工具
数据结构·python·算法·gui·排序·单词统计·查找