Skip to content

Instantly share code, notes, and snippets.

@rjdkolb
Last active July 12, 2018 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjdkolb/e83355814c47e6561bb7a4afca747bf3 to your computer and use it in GitHub Desktop.
Save rjdkolb/e83355814c47e6561bb7a4afca747bf3 to your computer and use it in GitHub Desktop.
Java Cloud Conference (2018) Caffeine Challenge. More about Caffeine : https://youtu.be/Xl1XBJLfIDU
public class DuplicateSumTest {
@Test
public void sumNonDuplicates() {
Assert.assertEquals("", 3, sumNonDuplicates(new int[]{1, 2}));
}
@Test
public void sumDuplicates() {
Assert.assertEquals("", 3, sumNonDuplicates(new int[]{2, 1, 2, 1}));
}
public int sumNonDuplicates(int[] input) {
//don't create another array or collection
return 0;
}
}
@GianPaoloBuffo
Copy link

return IntStream.of(input).distinct().sum();

@eegeeZA
Copy link

eegeeZA commented Jul 12, 2018

return 3;

@corneil
Copy link

corneil commented Jul 12, 2018

The Stream version will still create collections under the covers.

public int sumNonDuplicates(int[] input) {
    int sum = 0;
    int current = 0;
    Arrays.sort(input);
    for (int i = 0; i < input.length; i++) {
        int value = input[i];
        if (value != current) {
            sum += value;
            current = value;
        }
    }
    return sum;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment