【问题标题】:Least repeated/items appearing once in an array最少重复/项目在数组中出现一次
【发布时间】:2019-04-02 21:36:00
【问题描述】:

我正在尝试打印唯一项目、重复次数最多的项目和重复次数最少的项目,即数组中出现一次。在重复最少的部分,我没有得到任何输出,因为标志设置为 1 而不是预期的 0。

示例输入:

10
watch
laptop
iphone
watch
car
headset
laptop
watch
shoe
mobile

样本输出:

The unique items are
watch
laptop
iphone
car
headset
shoe
mobile
The maximum purchased item(s) are
watch
The minimum purchased item(s) are
iphone
car
headset
shoe
mobile 
import java.util.Arrays;
import java.text.ParseException;
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;

public class ItemDetails {
    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        int flag=0, flag1=0, count = 0, count1 = 0, count2 = 0;
        String maxname = null;
        int k;
//      String[] max = new String[k];
        Integer x = sn.nextInt();

        sn.nextLine(); 
        String[] names=new String[x];
        for (int i = 0; i<x; i++)
        {
            names[i] = sn.nextLine();
        }
        System.out.println("The unique items are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                        if (names[i].equals(names[j]))
                        { 
                    // got the unique element 
                            flag = 0;
                            break;
                        }
                        else 
                        {
                            flag = 1;
//                          break;
                        }
//                  break;
                }
                if (flag==1)
                {
                    ++count;
                    System.out.println(names[i]);

                }
            }
            System.out.println(count);  
        }
        System.out.println("The maximum purchased item(s) are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                    if (names[i].equals(names[j]))
                    {
                        count1++;
                        maxname = names[i];
                    }
                    else
                    {
                        count1 = 0;
                    }
                }

            }
            System.out.println(maxname);    
        }

        System.out.println("The minimum purchased item(s) are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                    if (names[i].equals(names[j]))
                    {
                        flag1 = 1;
                        break;
                    }
                }

                if (flag1==0)
                {
                    count2++;
                    System.out.println(names[i]);
                }
            }
            //System.out.println(maxname);  
        }
    }
}

【问题讨论】:

  • 需要在内循环前清除flag。
  • 安德烈亚斯 - 没找到你。能指点一下位置吗?
  • 您是说“最低购买量”部分是空的,对吧?该代码嵌套了for 循环。在外循环内部(i 循环),before 内循环(j 循环),您需要清除标志(flag1)。
  • 试过了,但结果与“独特物品”部分相同。
  • 如果你的输入是2 foo foo,那么你循环并看到第一个foo,然后是另一个foo,所以你跳过它。你看到第二个foo,因为它没有跟随另一个foo,你打印它。 糟糕!

标签: java arrays


【解决方案1】:

@艾伦 使用 Java 流可能会更简单,例如:

    List<String> items = new ArrayList<String>();
    // Fill List items with your data

    Map<String, Long> processed =items.stream()
            .collect(Collectors.groupingBy(
                            Function.identity(), Collectors.counting())                        
    );

    System.out.println ("Distinct items");
    processed.keySet().stream().forEach(item -> System.out.println(item));

    Long minCount = Collections.min(processed.values());
    Long maxCount = Collections.max(processed.values());

    System.out.println ("Least repeated items");
    processed.entrySet().stream().filter(entry -> entry.getValue().equals(minCount)).forEach(item -> System.out.println(item));        

    System.out.println ("Most repeated items");
    processed.entrySet().stream().filter(entry -> entry.getValue().equals(maxCount)).forEach(item -> System.out.println(item));

【讨论】:

  • 谢谢。实际上我试图在不使用流的情况下做到这一点。无论如何,谢谢。
【解决方案2】:

检索独特的项目:

public static Set<String> getUniqueItems(Collection<String> items) {
    return new HashSet<>(items);
}

使用给定的Function(使用Streams)检索购买的商品:

private static Set<String> getPurchasedItems(Collection<String> items, Function<Collection<Long>, Long> function) {
    Map<String, Long> map = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    final long count = function.apply(map.values());

    return map.entrySet().stream()
              .filter(entry -> entry.getValue() == count)
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

使用给定的Function(使用 POJO)检索购买的商品:

private static Set<String> getPurchasedItems(Collection<String> items, Function<Collection<Long>, Long> function) {
    Map<String, Long> map = new HashMap<>();

    for (String item : items)
        map.compute(item, (key, count) -> Optional.ofNullable(count).orElse(0L) + 1);

    final long count = function.apply(map.values());

    Set<String> res = new HashSet<>();

    for (Map.Entry<String, Long> entry : map.entrySet())
        if (entry.getValue() == count)
            res.add(entry.getKey());

    return res;
}

检索最多购买的物品:

public static Set<String> getMaximumPurchasedItems(Collection<String> items) {
    return getPurchasedItems(items, Collections::max);
}

检索最少购买的物品:

public static Set<String> getMinimumPurchasedItems(Collection<String> items) {
    return getPurchasedItems(items, Collections::min);
}

【讨论】:

  • 谢谢。实际上我试图在不使用流的情况下做到这一点。
【解决方案3】:

在最小的代码位置,在第二个循环之前设置flag1=0;,您还应该对数组进行排序以便能够应用此算法。除了这两个之外,您还需要将项目与之前进行比较,以确保您的算法能够正常工作

    System.out.println("The minimum purchased item(s) are");
    {
        Arrays.sort(names);
        for (int i = 0; i < x-1; i++) {
            flag1 = 0;
            for (int j = i + 1; j < x; j++) {
                if (names[i].equals(names[j]) || (i>1 && names[i].equals(names[i-1])) ) {
                    flag1 = 1;
                    break;
                }
            }

            if (flag1 == 0) {
                count2++;
                System.out.println(names[i]);
            }
        }
    }

【讨论】:

  • 非常感谢!这有帮助。
  • @Alan 那么您能否将其标记为已批准?至少给 +1
猜你喜欢
  • 2010-09-29
  • 1970-01-01
  • 2014-04-20
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
相关资源
最近更新 更多