获得最大价值

时间:2012-08-31 04:31:03

标签: java

我有许多形式配对:

  • itemid core
  • 1 2
  • 1 4
  • 1 3
  • 2 2
  • 2 5

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

  • itemid core
  • 1 4
  • 2 5

解?

3 个答案:

答案 0 :(得分:2)

使用Map<Integer, Integer>作为密钥,itemid作为其值,并在每次迭代中,将当前maximum值与新max(core)值进行比较1}}:

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)); 
}

<强> DEMO

答案 1 :(得分:1)

这将为您提供一个已排序的对列表,这里按核心升序排序:

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);
}
}

答案 2 :(得分:0)

您可以先按itemid对项目列表进行排序,然后使用核心等于itemid。 一旦你有一个排序列表,它将需要O(n)遍历所有元素和拾取最大相等itemid。 如果您需要实际代码,请告诉我。

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

相关问题