Skip to content

Commit

Permalink
Count absolute distincts in sorted array
Browse files Browse the repository at this point in the history
  • Loading branch information
AnghelLeonard committed Feb 27, 2020
1 parent e5048dc commit 57f5311
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Chapter10/CountDistinctAbsoluteSortedArray/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coding.challenge</groupId>
<artifactId>CountDistinctAbsoluteSortedArray</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>13</maven.compiler.target>
</properties>
<name>CountDistinctAbsoluteSortedArray</name>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package coding.challenge;

public final class Arrays {

private Arrays() {
throw new AssertionError("Cannot be instantiated");
}

public static int findAbsoluteDistinct(int[] m) {

if (m == null) {
return -1;
}

int count = m.length;

int left = 0;
int right = m.length - 1;

while (left < right) {

// remove duplicates elements from the left and right
while (left < right && m[left] == m[left + 1]) {
count--;
left++;
}

while (right > left && m[right] == m[right - 1]) {
count--;
right--;
}

// only one element is left
if (left == right) {
break;
}

int sum = m[left] + m[right];

// decrease the distinct count if zero sum pair is encountered
if (sum == 0) {

count--;

left++;
right--;
} else if (sum < 0) {

left++;
} else {

right--;
}
}

return count;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package coding.challenge;

public class Main {

public static void main(String[] args) {

int[] m = {-3, -3, -2, -1, -1, -1, 0, 1, 1, 1, 2, 2, 3, 5, 6, 7, 7};

int result = Arrays.findAbsoluteDistinct(m);

System.out.println("Array: " + java.util.Arrays.toString(m));
System.out.print("The number of distinct absolute values is: "
+ result);
}
}

0 comments on commit 57f5311

Please sign in to comment.