[Codility] [7–2] Fish (score 37%)
2 min readDec 14, 2021
【Lesson 7–2】: Fish 判斷魚往上下游,並且判斷是大魚或小魚,大魚可以吃掉對向游過來的小魚,假如對向是大魚會被吃掉 (score 37%,僅參考)
public static int Fish(int[] A, int[] B){int[] selDown = B.Select((v, i) => new { v, i }).Where(w => w.v == 1).Select(s => s.i).ToArray();// 第一次往下游的魚,代表前面魚都通過if (selDown.Length == 0 || selDown.Length == A.Length)return A.Length;System.Collections.Generic.Stack<int> st_down = new System.Collections.Generic.Stack<int>();System.Collections.Generic.Stack<int> st_up = new System.Collections.Generic.Stack<int>();//開始判斷第一次很下游的魚for (int i = 0; i < B.Length - 1; i++){if (i == 0){if (B[i] == 1)st_down.Push(A[i]);elsest_up.Push(A[i]);}if (B[i + 1] == 1)st_down.Push(A[i + 1]);elsest_up.Push(A[i + 1]);//int down_val = st_down.Peek();if (B[i + 1] == 0 && st_down.Peek() > A[i + 1]) //遇到往上游,而且是小魚{st_up.Pop();}else if (B[i + 1] == 0 && st_down.Peek() < A[i + 1]) //遇到往上游,而且是大魚{check_st(ref st_down, A[i + 1]);}}return st_up.Count + st_down.Count;}public static void check_st(ref Stack<int> st, int val){for (int i = 0; i < st.Count; i++){if (st.Peek() < val){st.Pop();}}}