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 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)