笔试最长子数组和最大子矩阵c#

来源:互联网 发布:mallat小波算法原理 编辑:程序博客网 时间:2024/06/05 22:33

今天笔试题记录下

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;        }


0 0