Last active
August 29, 2017 21:46
-
-
Save deyindra/9bb4d808712563e6044280d93bb31893 to your computer and use it in GitHub Desktop.
Find pair from Sorted Array
This file contains hidden or 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
//Time complexity O(N), Space Complexity O(1) | |
public static List<Pair<Integer, Integer>> getPairs(int[] array, final int sum){ | |
int start = 0; | |
int end = array.length-1; | |
List<Pair<Integer, Integer>> list = new ArrayList<>(); | |
while (start < end){ | |
int resultSum = array[start] + array[end]; | |
if(resultSum < sum){ | |
start++; | |
}else if (resultSum > sum){ | |
end --; | |
}else{ | |
list.add(Pair.of(array[start], array[end])); | |
start ++ ; | |
end --; | |
} | |
} | |
return list; | |
} |
This file contains hidden or 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
package org.idey.algo.ds; | |
import java.util.Map; | |
public interface Pair<K,V> extends Map.Entry<K,V> { | |
@Override | |
default V setValue(V value) { | |
throw new UnsupportedOperationException("Invalid operation"); | |
} | |
static <K,V> Pair<K,V> of(K key, V value) { | |
return new PairImpl<>(key,value); | |
} | |
class PairImpl<K,V> implements Pair<K,V>{ | |
private K key; | |
private V value; | |
private PairImpl(K key, V value) { | |
this.key = key; | |
this.value = value; | |
} | |
@Override | |
public K getKey() { | |
return key; | |
} | |
@Override | |
public V getValue() { | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment