编程题训练5

    xiaoxiao2021-03-26  68

    编程题训练5

    最大子数组

    给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

    样例

    给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

    解析文章

    public class Solution { public int maxSubArray(int[] nums) { // 参数校验 int max = Integer.MIN_VALUE; int curMax = 0; for(int i : nums){ curMax = curMax + i < i ? i : curMax+i; max = curMax < max ? max : curMax; } return max; } }

    删除排序数组中的重复数字

    给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。 不要使用额外的数组空间,必须在原地没有额外空间的条件下完成。

    样例

    给出数组A =[1,1,2],你的函数应该返回长度2,此时A=[1,2]。

    public class Solution { /** * @param A: a array of integers * @return : return an integer */ public int removeDuplicates(int[] nums) { // write your code here int i = 0; int numsLen = nums.length; while(i<numsLen-1){ if(nums[i]==nums[i+1]){ for(int j=i+1;j<numsLen-1;j++) nums[j]=nums[j+1]; numsLen-=1; }else i+=1; } return numsLen; } }

    合并排序数组 II

    合并两个排序的整数数组A和B变成一个新的数组。

    样例

    给出 A = [1, 2, 3, empty, empty], B = [4, 5]

    合并之后 A 将变成 [1,2,3,4,5]

    class Solution { /** * @param A: sorted integer array A which has m elements, * but size of A is m+n * @param B: sorted integer array B which has n elements * @return: void */ public void mergeSortedArray(int[] A, int m, int[] B, int n) { // write your code here //用库函数 // for(int i=0;i<n;i++) // A[m+i] = B[i]; // Arrays.sort(A); while (pa >= 0 && pb >= 0) { if (A[pa] >= B[pb]) A[p--] = A[pa--]; else A[p--] = B[pb--]; } while(pb >= 0) A[p--] = B[pb--]; } }
    转载请注明原文地址: https://ju.6miu.com/read-500378.html

    最新回复(0)