Display an integer array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Display an integer array相关的知识,希望对你有一定的参考价值。

Display an integer array of [1, 2, 3, 4, 5, 6, 7] in the following format 

1 4 6 
2 5 7 
3 

The method signature takes in an array of integers and the number of columns. In the above example, noOfCols = 3.
The columns should contain equal number of elements as much as possible.

 

public static void main(String[] args) { 
// TODO Auto-generated method stub 

int[] nums = { 1, 2, 3, 4, 5, 6, 7}; 
Problem.printArr(nums, 5); 
} 

private static void printArr(int[] nums, int numCols) { 

int numRows = nums.length / numCols; 
int numLastRow = nums.length % numCols; 
if (numLastRow > 0) { 
numRows++; 
} 

int[][] matrix = new int[numRows][numCols]; 
int arrIndex = 0; 

for (int i = 0; i < numCols; i++) { 
for (int j = 0; j < numRows; j++) { 
// If we‘re on the bottom row and over the number 
// of items to be put on it just skip this iteration 
if ((j == numRows - 1) && i >= numLastRow) { 
continue; 
} 
matrix[j][i] = nums[arrIndex]; 
arrIndex++; 
if (arrIndex >= nums.length) 
break; 
} 
if (arrIndex >= nums.length) 
break; 
} 

arrIndex = 0; 
for (int i = 0; i < numRows; i++) { 
for (int j = 0; j < numCols; j++) { 
if (matrix[i][j] > 0) 
System.out.print(String.format("%3d", matrix[i][j])); 
if (arrIndex >= nums.length) 
break; 
} 
System.out.println(); 
if (arrIndex >= nums.length) 
break; 
} 
} 

} 

  

以上是关于Display an integer array的主要内容,如果未能解决你的问题,请参考以下文章

Always an Integer 数论和字符串处理

leetcode1394. Find Lucky Integer in an Array

leetcode_easy_array1394. Find Lucky Integer in an Array

LeetCode --- 1394. Find Lucky Integer in an Array 解题报告

442. 找出数组中重复的元素 Find All Duplicates in an ArrayGiven an array of integers

leetcode 448 Find All Numbers Disappeared in an Array