获得最大值[关闭]

问题描述 投票:-4回答:3

我有很多形式的配对:

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

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

  • itemid核心
  • 1 4
  • 2 5

解?

java
3个回答
2
投票

使用以Map<Integer, Integer>为关键字的itemidmax(core)作为其值,并在每次迭代中,将当前的maximum值与新的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

DEMO


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

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.