蓝桥杯——数组
1、移动数组元素
package day3;
import java.util.Arrays;
public class Demo1 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
int k = 2;
int[] arr_new = f(arr,k);
for (int i : arr_new) {
System.out.print(i+",");
}
//或
System.out.println();
String str = Arrays.toString(arr_new);
System.out.println(str);
}
private static int[] f(int[] arr, int k) {
int n =arr.length;
k = k%n;
int[] new_arr = new int[n];
for (int i = 0; i < arr.length; i++) {
new_arr[(i+k) % n] = arr[i];
}
return new_arr;
}
}
结果
2、二维数组求和
package day3;
public class Demo3 {
public static void main(String[] args) {
int [][] arr= {{1,2,3},{4,5,6},{7,8,9}};
int result = sum_arr(arr);
System.out.println(result);
}
private static int sum_arr(int[][] arr) {
int sum = 0;
for (int[] is : arr) {
for (int is2 : is) {
sum+=is2;
}
}
return sum;
}
}
结果
45
3、二维数组x,y轴互换,转置二维矩阵
package day3;
public class Demo4 {
public static void main(String[] args) {
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int[] is : arr) {
for (int is2 : is) {
System.out.print(is2 + "\t");
}
System.out.println();
}
System.out.println("=======================");
int[][] newArr = f(arr);
for (int[] is : newArr) {
for (int is2 : is) {
System.out.print(is2 + "\t");
}
System.out.println();
}
}
private static int[][] f(int[][] arr) {
int row = arr.length;
int col = arr[0].length;
int[][] newArr = new int[row][col];
for (int i = 0; i < newArr.length; i++) {
for (int j = 0; j < newArr.length; j++) {
newArr[j][i] = arr[i][j];
}
}
return newArr;
}
}
结果
4、杨辉三角
package day3;
public class Demo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// for (int i = 0; i < 10; i++) {
// for (int j = 0; j < 10; j++) {
// System.out.print("外:"+i+"内:"+j);
// }
// System.out.println();
// }
int n = 6;
int [][] arr = new int [n+1][n+1];
for (int i = 1; i < arr.length; i++) {
for (int j = 1; j <=i; j++) {
if(i==1||i==j) {
arr[i][j]=1;
}else {
arr[i][j]=arr[i-1][j]+arr[i-1][j-1];
}
}
}
for (int i = 1; i < arr.length; i++) {
for (int j = 1; j <=i; j++) {
System.out.print(arr[i][j]+",");
}
System.out.println();
}
}
}
结果
eclipse常用快捷键
alt+/ :常用方法
ctrl+1:补全代码
5、在数组中寻找特定值
数组的每行从左到右升序排列,每列从上到下升序排列。
package day3;
public class Demo5 {
public static void main(String[] args) {
int[][] arr = { { 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 } };
boolean isf = f(arr,5);
System.out.println(isf);
}
private static boolean f(int[][] arr, int num) {
if(arr == null || arr[0].length == 0 || arr.length == 0) {
return false;
}
for (int[] is : arr) {
int start = 0;
int end = arr.length-1;
while(start<=end) {
int mid =start+(end-start)/2;
if(is[mid]==num) {
return true;
}else if(is[mid]>num) {
end = mid - 1;
}else {
start = mid +1;
}
}
}
return false;
}
}
结果
true