[ 命名建議 ] LeetCode 977. Squares of a Sorted Array #112
Answered
by
twy30
LPenny-github
asked this question in
Q&A
-
|
LeetCode: 線上教材: 再麻煩 @twy30 給予命名建議 orz 感激不盡 public int[] SortedSquares(int[] nums)
{
int[] input = nums;
int[] output = new int[input.Length];
int index = input.Length;
int firstIndex = 0, secondIndex = index -1;
do
{
int firstNumberSquare = input[firstIndex]*input[firstIndex];
// 當兩個 index 相同,就在 output 加入該平方數後,送出答案
if (firstIndex == secondIndex)
{
output[--index] = firstNumberSquare;
return output;
}
int secondNumberSquare = input[secondIndex]*input[secondIndex];
if (firstNumberSquare > secondNumberSquare)
{
output[--index] = firstNumberSquare;
++firstIndex;
}
else
{
output[--index] = secondNumberSquare;
--secondIndex;
}
} while (firstIndex <= secondIndex);
return new int[]{};
} |
Beta Was this translation helpful? Give feedback.
Answered by
twy30
Jan 5, 2021
Replies: 1 comment 5 replies
-
|
你好 😊 int index = input.Length;
int firstIndex = 0, secondIndex = index -1; int firstNumberSquare = input[firstIndex]*input[firstIndex];
int secondNumberSquare = input[secondIndex]*input[secondIndex];在這個案例中,是從一個「一維陣列」的 頭/尾 、 始/終 兩個方向向中間夾擊,所以可以試試這樣做:
可以參考看看 😊 |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
LPenny-github
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@LPenny-github
你好 😊
index可以換成outputIndexoutputIndex初始化為output.Length - 1do-while迴圈中,從--index改成index--input.Length與output.Length的值會是一樣的,但我會選使用output.Length,語意上比較一致 😊在這個案例中,是從一個「一維陣列」的 頭/尾 、 始/終 兩個方向向中間夾擊,所以可以試試這樣做:
first(第一),second(第二) 可以換成head(頭),tail(尾)start(始),end(終)outputIndex呼應,寫成像這樣:headInputIndex,tailInputIndexinput.Length - 1來初始化secondIndex/tailInputIndex可…