2018-07-31 21:03
浏览 296


say I have an int slice containing the following numbers: 2781,4706,1347,1192,3087,2920,198,2312,930,3284,1677,3687,2011,4107,4148,4195,2159,1263,2918,2503

I want to sort them based on how close they are away from a certain value. For example, say my value was 1200.

My slice after being sorted would be: 1192,1263,1347,1677,2011,2159,2312,2503,2781,2918,2920,3087,3284,3687,4107,4148,4195,4706,930,198

I tried the approach of iterating through the array, subtracting my specified value, then sorting in ascending order ultimately adding the value again to return to my original number. This approach wouldn't work in all test cases, and I know its bad practice since I'm mutating the array.

图片转代码服务由CSDN问答提供 功能建议

说我有一个包含以下数字的整数切片:2781,4706,1347,1192,3087,2920,198 ,2312,930,3284,1677,3687,2011,4107,4148,4195,2159,1263,2918,2503

我想根据距离它们的距离来对其进行排序 一个特定值。 例如,假设我的值为1200。

排序后的切片为:1192,1263,1347,1677,2011,2159,2312,2503,2781 ,2918,2920,3087,3284,3687,4107,4148,4195,4706,930,198

我尝试遍历数组的方法,减去指定的值,然后升序排序 最终再次添加该值以返回到我的原始编号。 这种方法并非在所有测试用例中都行得通,而且由于对数组进行了变异,因此我知道它的坏习惯。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题