Reputation: 153
I have an array that contains numbers.
I got the two minimum values (can be the same number) of this array in O(N) but i cant figure out how to get the index of this two values.
For example: in {1,2,3,1,5} the answer will be index 0 and index 3. this is the code i'm using:
public static void minMin(int arr[]){
int min1 = weights[0], min2 = weights[1];
if(min1 > min2){
int temp = min1;
min1 = min2;
min2 = temp;
}
for (int i = 2; i < weights.length; i++) {
if(weights[i] < min1){
int temp = min1;
min1 = weights[i];
min2 = temp;
}else if(weights[i] < min2){
min2 = weights[i];
}
}
}
Upvotes: 0
Views: 1066
Reputation: 140613
In addition to the local variables that keep the minimum values you need variables for the indexes, too.
You initiatilaze them with 0/1 and update them whenever you change the other variables.
Further thinking about this: one other option works without more variables. Storing value + index is convenient (the comment is correct though, you would probably use a distinct class to do that) but not mandatory. Because you can always fetch the value when you have an index!
In that sense: you could change your code to remember indixes only.
Upvotes: 5
Reputation: 240
Ghostcat already gave the answer, you just didnt understand:
I have only one index because its one for loop and i need the index's of two elements..
Just create more variables:
public static void main(String[] args) {
minMin(new int[] { 1, 2, 3, 1, 5 });
}
// Careful: this code only works for arr.lengh > 1
public static void minMin(int arr[]) {
int min1 = arr[0];
int min2 = arr[1];
int index1 = 0;
int index2 = 1;
if (min1 > min2) {
int temp = min1;
min1 = min2;
min2 = temp;
index1 = 1;
index2 = 0;
}
for (int i = 2; i < arr.length; i++) {
if (arr[i] < min1) {
int temp = min1;
min1 = arr[i];
min2 = temp;
index2 = index1;
index1 = i;
} else if (arr[i] < min2) {
min2 = arr[i];
index2 = i;
}
}
System.out.println("Smallest: " + min1 + ", index " + index1);
System.out.println("2nd smallest: " + min2 + ", index " + index2);
}
Output:
Smallest: 1, index 0
2nd smallest: 1, index 3
Upvotes: 1