zoukankan      html  css  js  c++  java
  • Longest Aritemetic Slices of Two sorted arrays

    package _interview_question
    
    /**
     * we have 2 arrays in sorted order, no duplicates.
    we need find the max continuous length AP [arithmetic prog] in the first array by adding 0 or more elements from the second array
    example,
    A= [4,8,13]
    B=[0,9,12]
    ANSWER = 4, because: [0,4,8,12]
     * */
    class Solution15 {
        /*
        * solution: merge two sorted array and find out longest arithmetic slices,
        * Time complexity:O(n^3), Space complexity:O(n)
        * */
        fun longestArithemeticSlices(nums1: IntArray, nums2: IntArray): Int {
            //merge two sorted array
            val n = nums1.size + nums2.size
            val array = IntArray(n)
            var i = 0
            var j = 0
            var index = 0
            while (i < nums1.size && j < nums2.size) {
                if (nums1[i] < nums2[j]) {
                    array[index++] = nums1[i]
                    i++
                } else {
                    array[index++] = nums2[j]
                    j++
                }
            }
            while (i < nums1.size) {
                array[index++] = nums1[i]
                i++
            }
            while (j < nums2.size) {
                array[index++] = nums2[j]
                j++
            }
            //find out longest arithmetic
            var max = 0
            for (i in 0 until n) {
                for (j in i + 1 until n) {
                    val diff = array[j] - array[i]
                    //for example: 1,2,3,4, A[j]=2, diff=1, so next should be 2+1
                    var next = array[j] + diff
                    //because has number 1,2, so current length is 2
                    var currentMax = 2
                    for (k in j + 1 until n) {
                        if (array[k] == next) {
                            currentMax++
                            next = array[k] + diff
                        }
                        max = Math.max(currentMax,max)
                    }
                }
            }
            return max
        }
    }
  • 相关阅读:
    小球与盒子的故事
    2020.1.11 考试总结
    P4249 [WC2007]剪刀石头布
    P3825 [NOI2017]游戏
    BZOJ 2238 Mst
    P4240 毒瘤之神的考验
    生成函数(严重残缺)
    Min_25
    P3455 [POI2007]ZAP-Queries
    P3233 [HNOI2014]世界树
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13788680.html
Copyright © 2011-2022 走看看