Skip to content

Instantly share code, notes, and snippets.

View alexandervasyuk's full-sized avatar

alexandervasyuk

View GitHub Profile
@alexandervasyuk
alexandervasyuk / matrixRegionSumNaive
Created October 2, 2014 17:50
MatrixRegionSumNaive
public int matrixRegionSumNaive(int[][] matrix, Coordinate A, Coordinate D) {
int result = 0;
for (int j = A.y; j < matrix.length; j++) {
for (int i = A.x; i < matrix[0].length; i++) {
result += matrix[i][j];
}
}
return result;
}
@alexandervasyuk
alexandervasyuk / pairsThatSumUpToKOptimized
Created October 1, 2014 23:59
pairsThatSumUpToK Optimized
public static List<Pair> pairsThatSumUpToK(int[] a, int k) {
HashSet<Integer> set = new HashSet<Integer>();
List<Pair> result = new ArrayList<Pair>();
for (int i = 0 ; i < a.length; i++) {
int lookup = k - i;
if (set.contains(lookup)) {
result.add(new Pair(lookup, i));
} else {
set.add(i);
}
@alexandervasyuk
alexandervasyuk / pairsThatSumUpToK
Last active August 29, 2015 14:07
Given an integer array, output all pairs that sum up to a value k
public static List<Pair> pairsThatSumUpToK(int[] a, int k) {
Arrays.sort(a);
List<Pair> result = new ArrayList<Pair>();
int left = 0;
int right = a.length-1;
while(left < right) {
int sum = a[left] + a[right];
if (sum < k) left++;
else if (sum > k) right--;
@alexandervasyuk
alexandervasyuk / gist:fb24a5aa16bfee1a9755
Created September 26, 2014 18:10
Partition linked list around x
public Node partition(Node node, int x) {
Node lessHead, lessTail, greaterHead, greaterTail;
while (node != null) {
Node next = node.next;
node.next = null;
if (node.data < x) {
if (lessHead == null) {
lessHead = lessTail = node;
} else {