Created
June 6, 2017 21:40
-
-
Save artlovan/90592068fffcc5c900d7152a4d69a670 to your computer and use it in GitHub Desktop.
CountNegativeIntegersInMatrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class CountNegativeIntegersInMatrix { | |
public static void main(String[] args) { | |
int[][] data = new int[][]{ | |
{-3, -2, -1, 0, 1, 2, 4, 6, 7, 8}, | |
{-3, -2, -1, 1}, | |
{-2, 2, 3, 4}, | |
{4, 5, 7, 8} | |
}; | |
if (solution1(data) != 7) throw new IllegalStateException(String.format("expected %d, got %d", 7, solution1(data))); | |
data = new int[][]{ | |
{-3, -2, -1, 0}, | |
{-3, -2, -1, 1}, | |
{-2, 2, 3, 4}, | |
{4, 5, 7, 8} | |
}; | |
if (solution1(data) != 7) throw new IllegalStateException(String.format("expected %d, got %d", 7, solution1(data))); | |
data = new int[][]{ | |
{-3, -2, -1, 0}, | |
{-1, 1}, | |
{-2, 2, 3, 4}, | |
{4, 5, 7, 8} | |
}; | |
if (solution1(data) != 5) throw new IllegalStateException(String.format("expected %d, got %d", 5, solution1(data))); | |
data = new int[][]{ | |
{-3, -2, -1, 0}, | |
{-1, 1}, | |
{0, 2, 3, 4}, | |
{4, 5, 7, 8} | |
}; | |
if (solution1(data) != 4) throw new IllegalStateException(String.format("expected %d, got %d", 4, solution1(data))); | |
data = new int[][]{ | |
{0}, | |
{1}, | |
{0, 2, 3, 4}, | |
{4, 5, 7, 8} | |
}; | |
if (solution1(data) != 0) throw new IllegalStateException(String.format("expected %d, got %d", 0, solution1(data))); | |
} | |
private static int solution1(int[][] data) { | |
int counter = 0; | |
for (int i = 0; i < data.length; i++) { | |
counter += bin(data[i]); | |
System.out.print("."); | |
} | |
System.out.println(); | |
return counter; | |
} | |
private static int bin(int[] data) { | |
int min = 0; | |
int max = data.length; | |
int mid = (max + min) / 2; | |
List<Integer> list = new ArrayList<>(); | |
while (true) { | |
if (list.contains(mid)) { | |
return data[mid] < 0 ? mid + 1 : mid; | |
} | |
if (data[mid] < 0) { | |
list.add(mid); | |
min = mid + 1; | |
mid = (max + min) / 2; | |
} else if (data[mid] > 0) { | |
list.add(mid); | |
max = mid - 1; | |
mid = (max + min) / 2; | |
} else if (data[mid] == 0) { | |
return mid; | |
} | |
System.out.print("."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment