定义一个整数数组,找出连续3个元素之和是最大的,并输出这三个元素
输入:2 ,-6 ,3,-9 ,15,-10, 8
输出:15,-10, 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
public class ArrayTakeNum { public static void main(String[] args) { int[] arr = new int[]{2, -6, 3, -9, 15, -10, 8}; int max = arr[0] + arr[1] + arr[2]; int index = 0; for (int i = 0; i < arr.length - 2; i++) { int sum = arr[i] + arr[i+1] + arr[i+2]; if(sum > max){ max = sum; index = i; } } System.out.println("连续3个元素之和最大的三个数分别是:" + arr[index] + "," + arr[index+1] + "," + arr[index+2]); } }
|
让数组的每个位置去除以首位置的元素,得到的结果,作为该位置上的新值,并遍历
int型数组:[12,3,3,34,56,77,432]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class ArrayPrint { public static void main(String[] args) { int[] arr = new int[]{12,3,3,34,56,77,432};
for(int i = arr.length - 1; i >=0; i--){ arr[i] = arr[i]/arr[0]; }
for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } }
}
|