Problem:
Given an array of ints, swap the first and last elements in the array. Return the modified array. The array length will be at least 1.
swapEnds({1, 2, 3, 4}) → {4, 2, 3, 1}
swapEnds({1, 2, 3}) → {3, 2, 1}
swapEnds({8, 6, 7, 9, 5}) → {5, 6, 7, 9, 8}
Solution:
public int[] swapEnds(int[] nums) { int a = nums[0]; int b = nums[nums.length - 1]; nums[0] = b; nums[nums.length - 1] =a; return nums; }
public int[] swapEnds(int[] nums) {
ReplyDeleteint temp=nums[0];
nums[0]=nums[nums.length-1];
nums[nums.length-1]=temp;
return nums;
}
public int[] swapEnds(int[] nums) {
ReplyDeleteint last = nums[0];
int first = nums[nums.length - 1];
nums[0] = first;
nums[nums.length - 1] = last;
return nums;
}
public int[] swapEnds(int[] nums) {
ReplyDeleteint newArr[] = new int[nums.length];
for(int i=0;i<nums.length-1;i++)
newArr[i]=nums[i];
newArr[0]=nums[nums.length-1];
newArr[nums.length-1]=nums[0];
return newArr;
}
int [] newArray = new int[nums.length];
ReplyDeletefor(int i = 1; i < nums.length - 1; ++i)
newArray[i] += nums[i];
newArray[0] = nums[nums.length-1];
newArray[nums.length-1] = nums[0];
return newArray;