java - 我遇到了 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;
}
}
}
解决方案
空数组与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;
}
推荐阅读
- ghostscript - GhostScript 独特的文件命名
- javascript - 图表底部的多个 x 轴
- xslt - XSL 1.0 中的不同值
- cordova - phonegap 浏览器不支持带有 iframe 的 webvr
- google-apps-script - 使用 Google App Script 来自 google drive 的 OCR 图像
- aspnetboilerplate - 重置密码的正确方法是什么?
- javascript - 使用 Javascript 查找对象中的重复值
- python - 无法强制 virtualenv 使用 Python 3.5
- java - 如何减小 LineChart 上的线条宽度
- github - CircleCI/Github 拉取请求状态未显示