开发者

Creating a New Reverse Java Array

CodingBat > Java > Array-1 > reverse3:

Given an array of ints length 3, ret开发者_开发技巧urn a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.

public int[] reverse3(int[] nums) {
    int[] values = new int[3];
    for (int i = 0; i <= nums.length - 1; i++) {
        for (int j = nums.length-1; j >= 0; j--) {
            values[i] = nums[j];
        }
    }
    return values;
}

I can't get this to work properly, usually the last int in the array, becomes every single int in the new array


You don't want a two-level loop. Just have one loop:

for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
    values[i] = nums[j];
}

or, alternately, just don't track j sepearately, and do this:

for(int i = 0; i < nums.length; i++) {
    values[i] = nums[nums.length - 1 - i];
}


Unless this is a homework, why not just use Apache ArrayUtils'

ArrayUtils.reverse(nums)

Never re-invent the wheel :)


The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.

public int[] reverse3(int[] nums) {
    return new int[] { nums[2], nums[1], nums[0] };
}

See also:

  • CodingBat/Java/Array-1/reverse3
    • Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.


Firstly, while creating new array give it size of old array. Next, when you're reversing an array, you don't need two loops, just one:

int length = oldArray.length
for(int i = 0; i < length; i++)
{
  newArray[length-i-1] = oldArray[i]
}


You only want a single loop, but with indices going both ways:

public int[] reverse(int[] nums) {
    int[] back = new int[nums.length];
    int i,j;
    for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
        back[i] = nums[j];
    return back;
}


public int[] reverse3(int[] nums) {
 int rotate[]={nums[2],nums[1],nums[0]};
 return rotate;
}


This code gives correct output:-

public int[] reverse3(int[] nums) {
  int[] myArray=new int[3];
  myArray[0]=nums[2];
  myArray[1]=nums[1];
  myArray[2]=nums[0];
  return myArray;
}


I got this with Python.. So you can get the idea behind it

def reverse3(nums):
num = []
for i in range(len(nums)):
  num.append(nums[len(nums) - i - 1])
return num 


In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations. First of all, very bad logic to have two loops for a simple swap algorithm such as :

public static void reverse(int[] b) {
   int left  = 0;          // index of leftmost element
   int right = b.length-1; // index of rightmost element

   while (left < right) {
      // exchange the left and right elements
      int temp = b[left]; 
      b[left]  = b[right]; 
      b[right] = temp;

      // move the bounds toward the center
      left++;
      right--;
   }
}//endmethod reverse

or simplified:

for (int left=0, int right=b.length-1; left<right; left++, right--) {
    // exchange the first and last
    int temp = b[left]; b[left]  = b[right]; b[right] = temp;
}

Why go through all this pain, why dont you trust Java's built-in APIs and do something like

public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}


  public int[] reverse3(int[] nums) {
  int[] values = new int[nums.length];
  for(int i=0; i<nums.length; i++) {
   values[nums.length  - (i + 1)]=nums[i];
  }
  return values;
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜