第一题:
/*将数组中的数全部移动到末尾
*比如[0,1,0,3,12]移动后的期望数组为[1,3,12,0,0]
*/
public class MoveZeros {
public static void moveZeros(int[] nums) {
//找到第一个0开始的位置
int start = -1;
for(int i = 0;i < nums.length;i ++) {
if(nums[i] == 0) {
start = i;
break;
}
}
if(start == -1) { //不存在0
return;
}
else {
for(int j = start + 1;j < nums.length;j ++) {
if(nums[j] != 0) { //不为0就交换,同时start指针右移
int temp = nums[j];
nums[j] = nums[start];
nums[start] = temp;
start ++;
}
}
}
}
public static void main(String[] args) {
int[] nums = {11,0,1,0,23,0,12};
MoveZeros.moveZeros(nums);
for(int i : nums) {
System.out.print(i + " ");
}
}
}
第二题:
/* 假设存在矩阵
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 要求将矩阵顺时针旋转90度打印
* 9 5 1
* 10 6 2
* 11 7 3
* 12 8 4
* 通过观察,可以发现是按列进行打印的
*/
public class PrintMatrix {
public void printMatrix(int[][] matrix) {
for(int j = 0;j < matrix[0].length;j ++) {
for(int i = matrix.length - 1;i >= 0;i --) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
new PrintMatrix().printMatrix(matrix);
}
}
2018携程春招后端开发实习题解
猜你喜欢
转载自blog.csdn.net/zhou15755387780/article/details/80654886
今日推荐
周排行