问题陈述:
给定一个int数组,计算数组是否包含某个值,该值在数组中跟随该值乘以10.我们将使用仅考虑从给定索引处开始的数组部分的约定。 call将索引传递为0.
示例:
public boolean array220(int[] nums, int index)
array220({1,2,20},0)→true
array220({3,30},0)→true
array220({3},0)→false **
我遇到了问题而无法解决问题。
答案 0 :(得分:3)
for (int i = index; i < nums.length - 1; i++)
if (nums[i] * 10 == nums[i + 1]) return true;
return false;
答案 1 :(得分:2)
我会给你一些伪代码来使用。
Let `nums` be my array
Let `i` be the starting index
Let `index` be `i + 1`
for all indices < array's length, iterate
Let currNum be `array[index - 1]`
if currNum times 10 equals `array[index]`
return true
increment index
return false because we found no numbers that we true
答案 2 :(得分:1)
我不会像Java程序那样给你答案,因为很多人都已经这样做了。
如有疑问,请尝试用英语(或任何其他母语)写出程序。如果您无法详细写出来,请写出您可以的内容,然后进行细化。
给定一个int数组,计算数组是否包含某个值,该值在数组中跟随该值乘以10.我们将使用仅考虑从给定索引处开始的数组部分的约定。 call将索引传递为0。
我们在这里知道什么?我们有一个数组和一个起始索引。那么,你想做什么?也许这有点复杂,所以如果我们手工做,你会怎么开始?
然后进一步完善:
您可能会注意到步骤2中存在一个小问题:您不希望将 all 循环到最后。因为如果你这样做,就不会有任何“下一个”元素来比较它。所以你真的要循环到倒数第二个元素。
继续提炼。在某些时候,您可以直接转换为Java或您想要的任何编程语言。 (如果最后一步不能这样做,则需要添加一个额外的步骤0:首先学习编程语言)
答案 3 :(得分:-1)
递归回答只是为了它的地狱...我也不会发布这是没有已经有效的答案。尝试并发布您尝试的内容。
public boolean array220(int[] nums, int index){
if(index >= nums.length - 1)
return false;
if(nums[index] * 10 == nums[index + 1]){
return true;
} else {
return array220(nums, ++index);
}
}