Last active
August 29, 2015 13:57
-
-
Save rayjcwu/9926885 to your computer and use it in GitHub Desktop.
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
public int countPair(int[] A, int X) { | |
int small = 0; | |
int big = 0; | |
int count = 0; | |
// find max big such that A[0] + A[big] <= X | |
while (big + 1 < A.length && A[0] + A[big + 1] <= X) { | |
big++; | |
} | |
// count use A[small] as smallest number, A[small + 1: big] as bigger number | |
while (big > small) { | |
if (A[small] + A[big] <= X) { | |
count += big - small; | |
small++; | |
} else /* A[small] + A[big] > X */ { | |
big--; | |
} | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment