H
H
hellcaster2019-02-22 13:59:24
Java
hellcaster, 2019-02-22 13:59:24

How can this program be optimized?

Hello. I have a program like this, but it runs too slowly. I have a limit of 1 sec and 256 MiB. But my program runs in 1.015 seconds. How can you speed it up? Perhaps there is something that immediately
catches the eye.

If anyone is interested in sample inputs
1 тест:
4 3
4 4 7 4
Результат:
4 4 4 7 или 7 4 4 4
2 тест:
7 3
3 2 1 7 4 2 1
Результат:
Oh sh*t

package mariaAndSweets;

import java.util.Collections;
import java.util.LinkedList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

final class Main {
  static final Scanner scanner = new Scanner(System.in);
  
  public static void main(String[] args) {
    final int number = scanner.nextInt(), min = scanner.nextInt();
    LinkedList<Integer> sweets = new LinkedList<>();
    LinkedList<Integer> copy = new LinkedList<>();
    
    for (int i = 0; i < number; i++) 
      sweets.add(scanner.nextInt());
    scanner.close();

    Set<Integer> set = new HashSet<>(sweets);
    copy.addAll(set);
    
    for (int i = 0; i < copy.size(); i++) {
      if (Collections.frequency(sweets, copy.get(i)) >= min) {
        Collections.sort(sweets);
        StringBuilder sb = new StringBuilder();
        
        for (Integer j : sweets)
          sb.append(j + " ");
        
        System.out.print(sb);
        return;
      }
    }

    System.out.print("Oh sh*t");
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Oparin, 2019-02-22
@losse_narmo

she won't accept the gift if there are no k consecutive candies of the same type

To do this, it is not necessary to sort the entire list
Yes, and instead of Collections.frequency, you can immediately count how many when entering

M
Marat Khayrutdinov, 2019-02-22
@distrik

Maybe it will be faster?

LinkedList<Integer> sweets = new LinkedList<>();
    StringBuilder sb = new StringBuilder();
    AtomicBoolean hasMinAmount = new AtomicBoolean(false);
    sweets.stream()
            .collect(Collectors.toMap(Integer::intValue, integer -> 1, Math::addExact))
            .forEach((candyName, amount) -> {
              if (amount >= min) {
                hasMinAmount.set(true);
              }
              for (int i = 0; i < amount; i++) {
                sb.append(candyName + " ");
              }
            });
    if (hasMinAmount.get()) {
      System.out.print(sb);
    } else {
      System.out.println("Oh sh*t");
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question