gudii9
asked on
swapEnds challenge
Hi,
I am working on belw challenge
http://codingbat.com/prob/p118044
i wrote as below and passed all tests.
How to improve my code and alternate ways of ding it. Please advise
I am working on belw challenge
http://codingbat.com/prob/p118044
i wrote as below and passed all tests.
public int[] swapEnds(int[] nums) {
int len=nums.length;
int[] newNums=new int[len];
for(int i=0;i<len;i++){
newNums[i]=nums[i];
}
newNums[0]= nums[len-1];
newNums[len-1]=nums[0];
return newNums;
}
How to improve my code and alternate ways of ding it. Please advise
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
it would be sufficient to loop for(int i=1;i<len-1;i++){
ASKER
int t=nums[0];
nums[0]=nums[nums.length-1 ];
nums[nums.length-1]=t;
return nums;
instead of above can we write like below without t?
nums[0]=nums[nums.length-1 ];
nums[nums.length-1]=nums[0 ];
return nums;
nums[0]=nums[nums.length-1
nums[nums.length-1]=t;
return nums;
instead of above can we write like below without t?
nums[0]=nums[nums.length-1
nums[nums.length-1]=nums[0
return nums;
ASKER
i think i got it. Since you are putting last in first so first needs to be saved somewhere to use later
ASKER
it would be sufficient to loop for(int i=1;i<len-1;i++){
this i will fix next time
instead of above can we write like below without t?No, nums[0] would have the same value as nums[nums.length-1];
nums[0]=nums[nums.length-1];
nums[nums.length-1]=nums[0];
return nums;