java- "-1" position
I have this question:
The method accepts an integer array as its input and returns a new array which is a permutation of the input array. The method fix34 rearranges the input array such that every 3 is immediately followed by a 4 (e.g. if there is a 3 at position i, there will be a 4 at position i+1). The method keeps the original positions of the 3s but may move any other number, moving the minimal amount of numbers. Assumptions regarding the input:
- The array contains the same number of 3's and 4's (for every 3 there is a 4)
- There are no two consecutive 3s in the array
- The matching 4 for a 3 at some position i is at position j where j > i
ok, so this is what I wrote:
public class Fix34 {
public static void main(String[] args){
int [] args1 ={3,1,2,3,5,4,4};
int[] args11=fix34(args1);
for (int i = 0; i<=args11.length-1;i++ ){
System.out.print(args11[i]+" ");}}
public static int pos (int[] arr){
int i= arr.length-1;
while (arr[i]!=4){
i=-1;
}
return i;
}
public static int[] fix34(int[] nums){
for(int i = 0; i<=nums.length-1; i++){
if (nums[i] == 3){
nums[pos(nums)]=nums[i+1];
nums[i+1]=4;
}
}
return nums;
}
}
when I insert arrays such {3,2,1,开发者_如何转开发4} it works, but with the array as written in the code, it gives me the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Fix34.pos(Fix34.java:15)
at Fix34.fix34(Fix34.java:25)
at Fix34.main(Fix34.java:6)
how come the arrays gets to -1 position?!
Thanks
you are setting it to -1 here:
i=-1;
Your issue in in this piece of code
public static int pos (int[] arr){
int i= arr.length-1;
while (arr[i]!=4){
i=-1;
}
return i;
}
If the last element in the array is 4 the while loop is never entered so arrays like 3, 1, 2, 4 are fine. Otherwise the loop is entered and i is set to -1. I think that you mean to decrement. In that case replace
i=-1
with
i--
or
i=i-1
and as mentioned in another answer make sure i doesn't go below 0.
I think you ment
i-= 1;
instead of that:
i=-1;
Whoa there that is a little overblown for this problem. Nested loops are they key here…come take a look
public int[] fix34(int[] nums) {
for(int a = 0; a < nums.length; a++){ //we see 4's first
for(int b = 0; b < nums.length - 1; b++){ //then the nested loop finds a 3
//length - 1 to stay in bounds, although not needed here...
if(nums[a] == 4 && nums[b] == 3){
//swap
int tmp = nums[b + 1];
nums[b + 1] = nums[a];
nums[a] = tmp;
}
}
}
return nums;
}
精彩评论