Monday, April 18, 2016

[Java][Answer] CodingBat Array-1 > maxEnd3()

Given an array of ints length 3, figure out which is larger, the first or last element in the array, and set all the other elements to be that value. Return the changed array.

maxEnd3([1, 2, 3]) → [3, 3, 3]
maxEnd3([11, 5, 9]) → [11, 11, 11]
maxEnd3([2, 11, 3]) → [3, 3, 3]

Answer 1:

public int[] maxEnd3(int[] nums) {
  int max = Math.max(nums[0],nums[2]);
  return new int[]{max,max,max};
}

Answer 2:

public int[] maxEnd3(int[] nums) {
  if (nums[0] >= nums[nums.length-1]) {
  nums[0] = nums[0];
  nums[1] = nums[0];
  nums[2] = nums[0];
  }
  else if (nums[0] <= nums[nums.length-1]) {
  nums[0] = nums[nums.length-1];
  nums[1] = nums[nums.length-1];
  nums[2] = nums[nums.length-1];
  }
  return new int[] { nums[0],nums[1],nums[2]};
}

Reference

http://www.javaproblems.com/2012/12/coding-bat-java-array-1-maxend3.html

No comments :

Post a Comment