From c3bbc6deb1e57062b46964d4c0705ada90f973b4 Mon Sep 17 00:00:00 2001 From: brendon <36212954+brendonmiranda@users.noreply.github.com> Date: Sat, 9 Nov 2024 20:44:15 +0000 Subject: [PATCH] improving lonely integer by reviewing it some time later --- .../java/hackerRank/week1/LonelyInteger.java | 24 +++++++++---------- .../hackerRank/week1/LonelyIntegerTest.java | 4 ++++ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/main/java/hackerRank/week1/LonelyInteger.java b/src/main/java/hackerRank/week1/LonelyInteger.java index ff35e6f..8dc80af 100644 --- a/src/main/java/hackerRank/week1/LonelyInteger.java +++ b/src/main/java/hackerRank/week1/LonelyInteger.java @@ -11,21 +11,19 @@ public class LonelyInteger { public int lonelyInteger(List a) { - Set integerSet = new HashSet<>(); - - long listSum = 0; - long setSum = 0; - - for (Integer i : a) { - integerSet.add(i); - listSum += i; - } - - for (Integer i : integerSet) { - setSum += i; + Set buffer = new HashSet<>(); + int sum = 0; + int sumOfUniqueElements = 0; + + for (int i : a) { + sum += i; + if (!buffer.contains(i)) { + sumOfUniqueElements += i; + buffer.add(i); + } } - return Long.valueOf((2 * setSum) - listSum).intValue(); + return (2 * sumOfUniqueElements) - sum; } diff --git a/src/test/java/hackerRank/week1/LonelyIntegerTest.java b/src/test/java/hackerRank/week1/LonelyIntegerTest.java index 36ca160..deacdcb 100644 --- a/src/test/java/hackerRank/week1/LonelyIntegerTest.java +++ b/src/test/java/hackerRank/week1/LonelyIntegerTest.java @@ -17,6 +17,10 @@ public void test() { Assertions.assertEquals(4, r); + r = lonelyInteger.lonelyInteger(List.of(1, 2, 3, 4, 5, 1, 2, 3, 4)); + + Assertions.assertEquals(5, r); + } }