Skip to content

Commit

Permalink
improving lonely integer by reviewing it some time later
Browse files Browse the repository at this point in the history
  • Loading branch information
brendonmiranda committed Nov 9, 2024
1 parent ef4e41a commit c3bbc6d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
24 changes: 11 additions & 13 deletions src/main/java/hackerRank/week1/LonelyInteger.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,19 @@ public class LonelyInteger {

public int lonelyInteger(List<Integer> a) {

Set<Integer> 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<Integer> 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;

}

Expand Down
4 changes: 4 additions & 0 deletions src/test/java/hackerRank/week1/LonelyIntegerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);

}

}

0 comments on commit c3bbc6d

Please sign in to comment.