英文:
Return an array with all negatives in a matrix
问题
int[] getNegatives(int[][] m) {
int countNegatives = 0; // 用于确定数组长度
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] < 0) {
countNegatives += 1;
}
}
}
int[] arr = new int[countNegatives];
int increase = 0; // 用于递增数组索引
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] < 0) {
arr[increase] = m[i][j];
increase += 1;
}
}
}
return arr;
}
英文:
I am new to programming and want to establish good habits, could I have done this in another and faster way?
int[] getNegatives(int[][] m) {
int countNegatives = 0; // used to create length of array
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] < 0) {
countNegatives += 1;
}
}
}
int[] arr = new int[countNegatives];
int increase = 0; // used to increment index of array
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] < 0) {
arr[increase] = m[i][j];
increase += 1;
}
}
}
return arr;
}
答案1
得分: 2
你可以使用 ArrayList 代替数组。这样你在创建数组之前就不需要知道确切的数字,还可以避免计数的步骤。
不过你需要使用 Integer,因为在 Java 的集合中不能放入原始数据类型。
List<Integer> getNegatives(int[][] m) {
List<Integer> negatives = new ArrayList<>();
for (int[] ints : m) {
for (int anInt : ints) {
if (anInt < 0) {
negatives.add(anInt);
}
}
}
return negatives;
}
如果你真的不想使用集合,你仍然可以通过使用 增强的 for 循环 来改进你的代码。
int[] getNegatives(int[][] m) {
int countNegatives = 0;
for (int[] ints : m) {
for (int anInt : ints) {
if (anInt < 0) {
countNegatives += 1;
}
}
}
int[] arr = new int[countNegatives];
int increase = 0;
for (int[] ints : m) {
for (int anInt : ints) {
if (anInt < 0) {
arr[increase++] = anInt;
}
}
}
return arr;
}
英文:
You could use an ArrayList instead of an array. That way you don't need to know the exact number before creating the array, and you can skip the counting.
You would need to use Integer though since you cant put primitives in Java Collections.
List<Integer> getNegatives(int[][] m) {
List<Integer> negatives = new ArrayList<>();
for (int[] ints : m) {
for (int anInt : ints) {
if (anInt < 0) {
negatives.add(anInt);
}
}
}
return negatives;
}
If you really don't want to use Collections you can still improve your code by using the enhanced for loop
int[] getNegatives(int[][] m) {
int countNegatives = 0;
for (int[] ints : m) {
for (int anInt : ints) {
if (anInt < 0) {
countNegatives += 1;
}
}
}
int[] arr = new int[countNegatives];
int increase = 0;
for (int[] ints : m) {
for (int anInt : ints) {
if (anInt < 0) {
arr[increase++] = anInt;
}
}
}
return arr;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论