c++ - 绝对值排序,使用自定义比较器

标签 c++ sorting lambda

背景:

我在一次 pramp 面试中被问到这个问题,我无法通过所有测试用例。

问题:

Absolute Value Sort

Given an array of integers arr, write a function absSort(arr), that sorts the array according to the absolute values of the numbers in arr. If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers.

Examples:

input: arr = [2, -7, -2, -2, 0]

output: [0, -2, -2, 2, -7]

我的尝试:

  std::sort(nums.begin(), nums.end(), [](int a, int b) {
    if(abs(a) < abs(b))
      return true;
    return a < b ? (a < 0 && abs(a) > b) : (b < 0 && abs(b) > a);
  });

例如,我通过了一些测试用例,但不是全部

Input: [2,-7,-2,-2,0]
Expected: [0,-2,-2,2,-7]
Actual: [0, -2, -7, 2, -2 ]

我觉得我只需要对我的 lambda 函数做一些小的调整,但我想不出来。

最佳答案

这可能有用

    std::sort(nums.begin(), nums.end(), [](int a, int b) {
    if(abs(a) != abs(b))
      return abs(a) < abs(b);
    return a < b;
  });

关于c++ - 绝对值排序,使用自定义比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58967981/

相关文章:

java - 是否有可用于任何 lambda 的无操作 (NOP) 的方法引用?

c++ - 如何检查指针何时被删除?

c++,在二维空间中生成均匀分布的菱形或三角形孔

algorithm - 什么是适合嵌入式系统的排序算法?

r - 按每行中 NA 的数量对数据进行排序

Java - PriorityQueue 与排序的 LinkedList

c++ - 为二叉搜索树复制构造函数编写辅助函数

c++ - Doxygen 如何按路径分隔类?

java - Eclipselink 忽略带有 lambda 表达式的实体类

c - 新的 C11 标准支持 lambda 吗?