1. 程式人生 > >筆試最長子陣列和最大子矩陣c#

筆試最長子陣列和最大子矩陣c#

今天筆試題記錄下

1。最長和為0的子陣列,例如1,2,3,-2,4,-3,2,-4,-2,0,6,7結果是2,3,-2,4,-3,2,-4,-2,0

大致思想是用遞迴的做法:如果一個序列自身不是最長的和為0的子陣列,那麼就比較這個序列去掉左邊一位和去掉右邊一位的兩個序列中最長的最長子陣列。

不過時間複雜度應該是n+2(n-1)+2(n-2)+....+2*1=O(n^2),回頭想想有沒有更高效的做法。

public static int[] getresult(int [] array,int start,int end)
        {
            int[] result = new int[2];
            result [1]=-1;
            int temp = 0;
            if(start>end)
                return result;
            for (int i = start; i <= end; i++)
            {

                temp += array[i];
            }
            if (temp == 0)
            {
                result[0] = start;
                result[1] = end;
                return result;
            }
            int[] Lresult = getresult(array, start, end - 1);
            int[] Rresult = getresult(array, start+1, end);
            return  (Lresult[1] - Lresult[0]) > (Rresult[1] - Rresult[0]) ? Lresult : Rresult;
        }

2。求矩陣的2*2的子矩陣裡所有元素和最大的。

全部遍歷一遍求解

public static int getresult(int[][] array,int m,int n)
        {
            if(m<2||n<2)
                return array [0][0];
            int max=array[0][0]+array[0][1]+array[1][0]+array[1][1] ;
            for(int i=1;i<m;i++)
                for (int j = 1; j < n; j++)
                {
                    if (max < array[i][j] + array[i - 1][j] + array[i][j - 1] + array[i - 1][j - 1])
                        max = array[i][j] + array[i - 1][j] + array[i][j - 1] + array[i - 1][j - 1];
                }
            return max;

        }