Problem:
Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more.
centeredAverage({1, 2, 3, 4, 100}) → 3
centeredAverage({1, 1, 5, 5, 10, 8, 7}) → 5
centeredAverage({-10, -4, -2, -4, -2, 0}) → -3
centeredAverage({1, 2, 3, 4, 100}) → 3
centeredAverage({1, 1, 5, 5, 10, 8, 7}) → 5
centeredAverage({-10, -4, -2, -4, -2, 0}) → -3
Solution:
public int centeredAverage(int[] nums) {
int min = nums[0];
int max = nums[0];
int sum = 0;
for (int i = 0; i < nums.length; i++){
sum += nums[i];
min = Math.min(min,nums[i]);
max = Math.max(max,nums[i]);
}
sum = sum - max - min;
sum = sum / (nums.length-2);
return sum;
}
public int centeredAverage(int[] nums) {
ReplyDeleteint av = 0;
Arrays.sort(nums);
for (int i = 1; i < nums.length-1; i++)
{
av += nums[i];
}
return av/(nums.length-2);
}
public int centeredAverage(int[] nums) {
ReplyDeleteArrays.sort(nums);
if(nums.length % 2 == 0){
return(nums[nums.length/2 - 1] + nums[nums.length/2]) / 2;
}
return nums[nums.length/2];
}
int len = nums.length;
ReplyDeleteint temp;
int sum=0;
for(int i=0; inums[j]){
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
sum+=nums[i];
}return (sum-(nums[0]+nums[len-1]))/(len-2);
public int centeredAverage(int[] a) {
ReplyDeleteint max=0, min=a[0], sum=0, n=a.length-2;
for(int i=0; imax) max=a[i];
if(a[i]<min) min=a[i];
}
sum=sum-max-min;
return sum/n;
}
public int centeredAverage(int[] a) {
Deleteint max=0, min=a[0], sum=0, n=a.length-2;
for(int i=0; imax) max=a[i];
if(a[i]<min) min=a[i];
}
sum=sum-max-min;
return sum/n;
}
With Java Stream
ReplyDeletepublic int centeredAverage(int[] nums) {
Arrays.sort(nums);
double Average = Arrays.stream(nums, 1, nums.length - 1)
.average()
.getAsDouble();
return (int)Average;
}
public int centeredAverage(int[] nums) {
ReplyDeleteint max = nums[0];
int min = nums[0];
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
if (nums[i] > max) {
max = nums[i];
}
if (nums[i] < min) {
min = nums[i];
}
}
sum = sum - max - min;
sum = sum / (nums.length-2);
return sum;
}