-5

我有很多对形式:

  • itemid核心
  • 1 2
  • 1 4
  • 1 3
  • 2 2
  • 2 5

我想获得其他 itemid 结果的最高分

  • itemid核心
  • 1 4
  • 2 5

解决方案?

4

3 回答 3

2

使用 aMap<Integer, Integer>作为itemid键,并max(core)作为其值,并在每次迭代中,将当前最大值与新的进行比较core

Map<Integer, Integer> maxMap = new HashMap<Integer, Integer>();
int[][] pairs = {
        { 1, 2 },
        { 1, 4 },
        { 1, 3 },
        { 2, 2 },
        { 2, 5 }
};
// Calculate max value for each itemid
for (int i = 0; i < pairs.length; i++) {
    int[] pair = pairs[i];
    Integer currentMax = maxMap.get(pair[0]);
    if (currentMax == null) {
        currentMax = Integer.MIN_VALUE;
    }
    maxMap.put(pair[0], Math.max(pair[1], currentMax));
}
// Print them
for (Integer itemId : maxMap.keySet()) {
    System.out.printf("%d %d\n", itemId, maxMap.get(itemId)); 
}

这将打印:

1 4
2 5

演示

于 2012-08-31T04:42:16.467 回答
2

这会给你一个排序的对列表,这里按核心升序排序:

package com.pair.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class MainClass {

/**
 * @param args
 */
public static void main(String[] args) {
    List<Pair> list = new ArrayList<Pair>();
    list.add(new Pair(1, 2));
    list.add(new Pair(1, 4));
    list.add(new Pair(1, 3));
    list.add(new Pair(2, 2));
    list.add(new Pair(2, 5));
    Collections.sort(list);
    System.out.println(list);
}

}

class Pair implements Comparable<Pair>{

public Pair(int i, int j) {
    itemId = i;
    core = j;
}

Integer itemId;

Integer core;

@Override
public String toString(){
    return itemId + " " + core;
}

public int compareTo(Pair compare) {
    return core.compareTo(compare.core);
}
}
于 2012-08-31T04:56:34.267 回答
0

您可以先按 itemid 对项目列表进行排序,如果 itemid 相等则按核心排序。一旦你对列表进行了排序,它将需要 O(n) 来遍历所有元素并为相等的 itemid 拾取最大值。如果您需要实际代码,请告诉我。

如果是 SQL。按 itemid 从表组中选择 itemid, max(core)。

于 2012-08-31T04:39:38.520 回答