給定來自CodingBat的任務notAlone:
如果陣列中的元素前后都有值,并且這些值與它不同,我們會說陣列中的元素是“單獨的” 。
回傳給定陣列的一個版本,其中給定值的每個實體都被其左側或右側較大的 值替換。
notAlone([1, 2, 3], 2) → [1, 3, 3]
notAlone([1, 2, 3, 2, 5, 2], 2) → [1, 3, 3, 5, 5, 2]
notAlone([3, 4], 3) → [3, 4]
我對這個問題的解決方案通過了絕大多數測驗,但不是全部:
public int[] notAlone(int[] nums, int val) {
int[] notAlone = new int[nums.length];
int largestNeighbour = 0;
if (notAlone.length >= 1) {
notAlone[0] = nums[0];
notAlone[notAlone.length - 1] = nums[nums.length - 1];
}
for (int i = 1; i < notAlone.length - 1; i ) {
if (nums[i] != val) {
notAlone[i] = nums[i];
}
if (nums[i] == val) {
notAlone[i] = Math.max(nums[i - 1], nums[i 1]);
}
}
return notAlone;
}
我的問題如下:
可以做些什么來修復我的解決方案?
是否可以使用Stream API解決此任務?
試驗結果
uj5u.com熱心網友回復:
如果陣列中的元素之前和之后有值,并且這些值與其不同,則陣列中的元素是“單獨的”
您的解決方案沒有通過所有測驗,因為您沒有檢查當前陣列元素是否是單獨的,即您只檢查當前元素是否等于目標值,但不檢查是否有相等的元素左邊或右邊。
這就是如何使用流來完成的,下面的代碼通過了CodingBat上的所有測驗:
public int[] notAlone(int[] nums, int val) {
return IntStream.range(0, nums.length)
.map(i -> isAlone(nums, val, i) ?
Math.max(nums[i - 1], nums[i 1]) : nums[i])
.toArray();
}
public boolean isAlone(int[] nums, int val, int i) {
return nums[i] == val && i > 0 && i < nums.length - 1
&& nums[i - 1] != val && nums[i 1] != val;
}
您提供的命令式代碼可以這樣修復(通過所有測驗):
public int[] notAlone(int[] nums, int val) {
if (nums.length == 0) return nums; // guarding against an empty array
int[] notAlone = new int[nums.length];
notAlone[0] = nums[0];
notAlone[nums.length - 1] = nums[nums.length - 1];
for (int i = 1; i < notAlone.length - 1; i ) {
if (nums[i] == val && nums[i - 1] != val && nums[i 1] != val) { // is "alone"
notAlone[i] = Math.max(nums[i - 1], nums[i 1]);
} else { // is not "alone"
notAlone[i] = nums[i];
}
}
return notAlone;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491243.html
上一篇:DoubleIfelse條件