对数组进行排序并检索排序的索引

时间:2019-12-23 20:17:44

标签: arrays algorithm sorting indexing time-complexity

我想按他的索引对数组进行排序。

看下面的代码:

<TouchableOpacity style={styles.btn}//add style to this component
in style 
 btn: {
    width: 58,
    height: 18,
    backgroundColor: "black",
    borderRadius: 2,
    alignSelf:'center'
  },

输出为:

var distances = [530, 0, 24, 335, 274, 591];

console.log(sortIndex(distances));

function sortIndex(toSort) {
  return toSort.map(
    (e,i) => {return {index: i, value: e};}
  ).sort(
    (a,b) => a.value - b.value
  ).map(
    (e,i) => {return e.index;},[]
  );
}

有人可以告诉我如何减少此代码段的复杂性吗?这个算法是[1, 2, 4, 3, 0, 5] ,我想知道您是否可以通过更好的解决方案来解决相同的问题?

有人在那里吗?谢谢。

2 个答案:

答案 0 :(得分:1)

通过创建数组的VStack { Spacer() .frame(height: 40) Text("Space me") Spacer() } 和复杂度为copy的索引hash结构,您可以获得更好的性能,因为只能迭代一次数组。

O(N)

因此,算法的最终复杂度是var distances = [530, 0, 24, 335, 274, 591]; var copy = Object.assign([], distances); var indexes = distances.reduce((hash, elem, i) => { hash[elem] = i; return hash; }, {}); sortIndex = (toSort) => toSort.sort().map(el => indexes[el]); console.log(sortIndex(copy));的复杂度加上sort函数的复杂度。

对于map,复杂度为sort

对于Θ(n log(n))方法,复杂度为map,因为您只需通过O(n)提供的将数组迭代一次即可 map 每个项目功能

答案 1 :(得分:0)

我实际上正在考虑使用TreeMap来解决问题,该TreeMap以升序保存键,并且可以将索引存储为键的值。这样,我们就可以正确索引重复的值,并且我想使用O(n log n)解决问题应该具有import java.util.*; public class HelloWorld { public static void main(String []args){ int arr[] = {530, 0, 24, 335, 274, 591}; int sortedIndexes[] = getSortedIndexes(arr); printSortedIndexes(sortedIndexes); } public static void printSortedIndexes(int[] printArr) { for (int element : printArr) { System.out.print(element + " "); } } public static int[] getSortedIndexes (int[] arr) { TreeMap<Integer, List<Integer>> map = new TreeMap<>(); for (int i = 0; i < arr.length; i++) { if (map.containsKey(arr[i])) { List<Integer> indexes = map.get(arr[i]); indexes.add(i); } else { List<Integer> indexes = new ArrayList<>(); indexes.add(i); map.put(arr[i], indexes); } } // Now get the elements from the LinkedHashMap int[] result = new int[arr.length]; int counter = 0; for( Map.Entry<Integer, List<Integer>> entry : map.entrySet()) { Integer key = entry.getKey(); List<Integer> indexes = entry.getValue(); for (int index : indexes) { result[counter] = index; counter++; } } return result; } } 的复杂性。

这是我的Java工作代码。

TreeMap

O(log n)本身的插入和查找复杂度为<Integer, Lis<Integer>>。我正在绘制List的映射,以便我们可以将给定数组中的值存储为键,并将值的索引存储为该键下的List<Integer>(这是为了处理重复的情况)。如果输入中没有重复项,我们可以摆脱TreeMap<Integer, Integer>,而只拥有async rateHistory(req) { try { const date = moment().subtract(10, "days"); return await Currencies.aggregate([ { $match: { currency: req.params.id } } ]) .unwind("history") .match({ "history.date": { $gte: date._d } }); } catch (e) { return new Error(e); } }

我希望能有所帮助。

相关问题