[ 命名建議 ] LeetCode 457. Circular Array Loop #127
Answered
by
twy30
LPenny-github
asked this question in
Q&A
-
|
LeetCode: 線上教材: 再麻煩 @twy30 給予命名建議 orz 感激不盡 public class Solution
{
public bool HasCircularArrayLoop(int[] nums)
{
int[] inputNumbers = nums;
if (inputNumbers.Length <= 1) { return false; }
for (int i = 0; i < inputNumbers.Length; i++)
{
if (inputNumbers[i] == 0) { continue; }
bool isForward = inputNumbers[i] > 0;
int slowIndex = i, fastIndex = i;
do
{
slowIndex = GetNextIndex(inputNumbers, isForward, slowIndex);
fastIndex = GetNextIndex(inputNumbers, isForward, fastIndex);
if (fastIndex != -1)
{
fastIndex = GetNextIndex(inputNumbers, isForward, fastIndex);
}
} while (slowIndex != -1 && fastIndex != -1 && slowIndex != fastIndex);
if (slowIndex != -1 && slowIndex == fastIndex)
{
return true;
}
}
return false;
}
int GetNextIndex(int[] inputNumbers, bool isForward, int currentIndex)
{
bool currentDirection = inputNumbers[currentIndex] > 0;
if (isForward != currentDirection)
{
return -1;
}
int nextIndex = currentIndex + inputNumbers[currentIndex] ;
while (nextIndex < 0)
{
nextIndex += inputNumbers.Length;
}
nextIndex %= inputNumbers.Length;
if (nextIndex == currentIndex)
{
nextIndex = -1;
}
return nextIndex;
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
twy30
Feb 13, 2021
Replies: 1 comment 3 replies
-
|
你好 😊 這些 "index" 變數的命名選得不錯,對比分明,很好懂 👍
bool currentDirection = inputNumbers[currentIndex] > 0;這裡我會把 例如說,可以比較一下以下兩者的感覺 if (isForward != isCurrentDirectionForward)這讀起來是「如果 是向前 不等於 目前方向是向前」,是在比較兩個 if (isForward != currentDirection)乍看之下可能會讀成「如果 是向前 不等於 目前的方向」。 while (nextIndex < 0)
{
nextIndex += inputNumbers.Length;
}
nextIndex %= inputNumbers.Length;這裡應該可以改寫成: if (nextIndex < 0)
{
nextIndex = inputNumbers.Length - -nextIndex % inputNumbers.Length;
}
else
{
nextIndex %= inputNumbers.Length;
}可以少個 |
Beta Was this translation helpful? Give feedback.
3 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" 變數的命名選得不錯,對比分明,很好懂 👍
slowIndex,fastIndexcurrentIndex,nextIndex這裡我會把
currentDirection改成isCurrentDirectionForward;與出現在其它多處的isForward更有一致性 🤔例如說,可以比較一下以下兩者的感覺
這讀起來是「如果 是向前 不等於 目前方向是向前」,是在比較兩個
bool變數。乍看之下可能會讀成「如果 是向前 不等於 目前的方向」。
這裡應該可以改寫成: