首页 > 解决方案 > 我遇到了 Codility 问题,如果我使用 A == null 仍然会遇到运行时错误

问题描述

我遇到了 Codility 问题,如果我使用 A == null 仍然会遇到运行时错误。问题:给定一个由 N 个整数组成的数组 A。数组的旋转意味着每个元素右移一个索引,并且数组的最后一个元素移动到第一个位置。

遇到错误的地方: input ([],1) 问题是 null 不验证 A 的值吗?

class Solution {
public int[] solution(int[] A, int K) {
  if(A == null){
    return A;
  }
 for(int y = 0; y < K; y++){
    int temp = A[A.length - 1];
        for(int x = A.length - 1; x > 0; x --){
            A[x] = A[x - 1];
        }
        A[0] = temp;
    }

    return A;
}

因此,如果我尝试使用 Try catch 并且它有效,而不是使用。

class Solution {
public int[] solution(int[] A, int K) {


try{
for(int y = 0; y < K; y++){
    int temp = A[A.length - 1];
        for(int x = A.length - 1; x > 0; x --){
            A[x] = A[x - 1];
        }
        A[0] = temp;
    }

    return A;
}
catch(ArrayIndexOutOfBoundsException e){
    return A;
}
} 
}

标签: java

解决方案


空数组与null. 您还需要检查空数组。因此try...catch,您可以这样做:

public int[] solution(int[] A, int K) {
  if(A == null || A.length == 0) { // here!
    return A;
  }
 for(int y = 0; y < K; y++){
    int temp = A[A.length - 1];
        for(int x = A.length - 1; x > 0; x --){
            A[x] = A[x - 1];
        }
        A[0] = temp;
    }

    return A;
}

推荐阅读