Created
May 31, 2015 21:16
-
-
Save jingz8804/53955bbaf817a6c2e179 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 Set<Integer> pickDistinctNumbers(int k, int[] numbers){ | |
if(numbers == null || numbers.length == 0) return null; | |
int len = numebrs.length; | |
if(k <= 0 || k > len) return null; // ask about these situations. this is just an example | |
Set<Integer> result = new HashSet<Integer>(); // Sets.newHashSet() if you use Google Guava | |
int size = 0; | |
while(size < k){ | |
int picked = (int) (Math.random() * len); | |
if(result.add(numbers[picked])) size++; | |
} | |
return result; | |
} |
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 Set<Integer> pickDistinctNumbers(int k, int[] numbers){ | |
if(numbers == null || numbers.length == 0) return null; | |
int len = numebrs.length; | |
if(k <= 0 || k > len) return null; // ask about these situations. this is just an example | |
Set<Integer> result = new HashSet<Integer>(); // Sets.newHashSet() if you use Google Guava | |
int size = 0; | |
while(size < k){ | |
int picked = (int) (Math.random() * len); | |
result.add(numbers[picked]); | |
size++; | |
numbers[picked] = numbers[len-1]; | |
len--; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment