You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:
2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.
0, if none of the previous conditions holds.
Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
我的初步解題思路是
public class Solution {
public int sumOfBeauties(int[] nums) {
int n = nums.length;
// 存儲每個元素美麗度的矩陣
int[] beauty = new int[n];
// 遍歷判斷每個元素的美麗度
for (int i = 1; i <= n - 2; i++) {
boolean leftSmaller = true; // 判斷左邊是否所有元素都小於i值
boolean rightBigger = true; // 判斷右邊是否所有元素都大於i值
// 檢查左邊的所有元素
for (int j = 0; j < i; j++) {
if (nums[j] >= nums[i]) {
leftSmaller = false;
break;
}
}
// 檢查右邊的所有元素
for (int k = i + 1; k < n; k++) {
if (nums[k] <= nums[i]) {
rightBigger = false;
break;
}
}
// 美麗度2分
if (leftSmaller && rightBigger) {
beauty[i] = 2;
}
// 美麗度1分
else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
beauty[i] = 1;
}
}
// 加總美麗度數組
int beautySum = 0;
for (int i = 1; i <= n - 2; i++) {
beautySum += beauty[i];
}
return beautySum;
}
}
丟去leetcode看結果!
雖然成功了,但感覺我的方法有點暴力...
不過因為是第一次嘗試中等難度,我想應該有寫出來就算合格了:D