track numbers in array java [duplicate]
Possible Duplicate:
Keep track of the lowest numbers in an array
I am trying to keep track of the lowest numbers in an array. And it works PART of the time and I just can't figure it out why its doing this
for (int i = 0; i < candidate.length; i++) {
for (int j = 1; j < candidate.length; j++) {
if (candidate[j] < candidate[i]) {
System.out.println(candidate[j]+ " "+candidate[i]);
开发者_Go百科 if(!tracking.contains(dictionary.get(j))) {
tracking.add(dictionary.get(j));
System.out.println(dictionary.get(j));
writeOut.add(space+dictionary.get(j)+" removed");
}
min[i] = j;
}
}
}
And it works for numbers like
2
2
1
2
1
but not for numbers like :
3
3
2
4
4
for this it gets 2 and three when clearly the lowest number is 2!
Why don't you just put your numbers in a
TreeSet<Integer> set = ...
And retrieve the lowest number with
Integer lowest = set.first();
But since you have to do it with an array because of severe prosecution in your jurisdiction, this is how you can do it:
int[] array = ...
// If your array is empty, then you will get MAX_VALUE as a result.
int lowest = Integer.MAX_VALUE;
for (int i : array) {
lowest = Math.min(i, lowest);
}
for (int i = 0; i < candidate.length; i++) {
for (int j = 0; j < candidate.length; j++) {
use this instead of what you have used:
for (int i = 0; i < candidate.length; i++) {
for (int j = 1; j < candidate.length; j++) {
The following method will return the first all positions of the minimum value in an integer array as a list. So it will return a list with values 2
and 3
for the input {4,3,1,1,5}
public static List<Integer> findPositionsOfLowestNumber(int[] values) {
List<Integer> result = new ArrayList(); // start with an empty list
int min = Integer.MAX_VALUE; // initial min value
for (int i = 0; i < values.length; i++) {
if (values[i] < min) {
min = values[i];
result.clear();
result.add(i);
} else if (values[i] == min) {
result.add(i);
}
}
return result;
}
Kept it simple - try to improve it later by looking at Math.min
or the enhanced for loop (if you're interested in the lowest value rather then it's position in the array)
精彩评论