gpt4 book ai didi

c++ - 如何在 C++ 中对包含负数和正数的字符串数组进行排序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:35:03 24 4
gpt4 key购买 nike

String str[]={"-123","89","-10","456"};

str is an array of strings, with each string in the format of an integer, and you have to perform sorting on this array in O(n log n) time.

The strings in str can represent both positive and negative integers. The maximum length of these strings is 1024 characters.

我知道这个问题的一个解决方案是将字符串转换为数字,然后将它们与此分开进行比较;这个问题还有其他解决方案吗?

最佳答案

另一种解决方案是实现您自己的比较功能:

  • 检查两个字符串的第一个字符。如果一个以数字开头,另一个以-开头,则以-开头的字符串是较小的数字。
  • 如果两个字符串都以数字开头,则比较字符串的长度字符串。较短的字符串是较小的数字。如果两个字符串长度相同,执行标准字符串比较。
  • 如果两个字符串都以-开头,则比较字符串的长度字符串。字符串越长,数字越小。如果两个字符串都是相同的长度,执行标准字符串比较,但取反结果。

关于c++ - 如何在 C++ 中对包含负数和正数的字符串数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58516048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com