Kotlin安卓算法总结

Kotlin 安卓算法优化指南

排序算法优化

1. 快速排序

// 使用三向切分的快速排序,对包含大量重复元素的数组更高效
fun optimizedQuickSort(arr: IntArray, low: Int = 0, high: Int = arr.lastIndex) {
    if (high <= low) return
    
    var lt = low
    var gt = high
    val pivot = arr[low]
    var i = low + 1
    
    while (i <= gt) {
        when {
            arr[i] < pivot -> arr.swap(lt++, i++)
            arr[i] > pivot -> arr.swap(i, gt--)
            else -> i++
        }
    }
    
    optimizedQuickSort(arr, low, lt - 1)
    optimizedQuickSort(arr, gt + 1, high)
}

2. 插入排序优化小数组

// 对小数组使用插入排序更高效
fun hybridSort(arr: IntArray, threshold: Int = 15) {
    if (arr.size <= threshold) {
        insertionSort(arr)
    } else {
        quickSort(arr)
    }
}

private fun insertionSort(arr: IntArray) {
    for (i in 1 until arr.size) {
        val key = arr[i]
        var j = i - 1
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j]
            j--
        }
        arr[j + 1] = key
    }
}

搜索算法优化

1. 二分查找

// 使用插值查找优化均匀分布数据的查找
fun interpolationSearch(arr: IntArray, target: Int): Int {
    var low = 0
    var high = arr.size - 1
    
    while (low <= high && target >= arr[low] && target <= arr[high]) {
        val pos = low + ((target - arr[low]) * (high - low)) / (arr[high] - arr[low])
        
        when {
            arr[pos] == target -> return pos
            arr[pos] < target -> low = pos + 1
            else -> high = pos - 1
        }
    }
    return -1
}

2. 优化的BFS

// 添加层级信息和提前终止条件的BFS
fun optimizedBfs(
    graph: Map<Int, List<Int>>, 
    start: Int, 
    target: Int? = null,
    maxLevel: Int = Int.MAX_VALUE
): Pair<List<Int>, Map<Int, Int>> {
    val visited = mutableListOf<Int>()
    val levels = mutableMapOf<Int, Int>().apply { put(start, 0) }
    val queue = ArrayDeque<Int>().apply { add(start) }
    
    while (queue.isNotEmpty()) {
        val node = queue.removeFirst()
        val currentLevel = levels[node] ?: 0
        
        if (currentLevel > maxLevel) break
        if (node !in visited) {
            visited.add(node)
            if (node == target) break
            
            graph[node]?.forEach { neighbor ->
                if (neighbor !in levels) {
                    levels[neighbor] = currentLevel + 1
                    queue.add(neighbor)
                }
            }
        }
    }
    return Pair(visited, levels)
}

数据结构算法优化

1. 链表反转

// 尾递归优化的链表反转
fun tailRecReverseList(head: ListNode?): ListNode? {
    tailrec fun reverse(prev: ListNode?, current: ListNode?): ListNode? {
        if (current == null) return prev
        val next = current.next
        current.next = prev
        return reverse(current, next)
    }
    return reverse(null, head)
}

2. 树遍历

// 迭代式树遍历,避免递归栈溢出
fun iterativeInorderTraversal(root: TreeNode?): List<Int> {
    val result = mutableListOf<Int>()
    val stack = ArrayDeque<TreeNode>()
    var current = root
    
    while (current != null || stack.isNotEmpty()) {
        while (current != null) {
            stack.push(current)
            current = current.left
        }
        current = stack.pop()
        result.add(current.`val`)
        current = current.right
    }
    return result
}

动态规划优化

1. 空间优化的斐波那契

// 使用矩阵快速幂将时间复杂度降至O(log n)
fun matrixFib(n: Int): Int {
    if (n <= 1) return n
    
    fun multiply(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> {
        return Array(2) { i ->
            IntArray(2) { j ->
                a[i][0] * b[0][j] + a[i][1] * b[1][j]
            }
        }
    }
    
    fun power(matrix: Array<IntArray>, n: Int): Array<IntArray> {
        if (n == 1) return matrix
        val half = power(matrix, n / 2)
        return if (n % 2 == 0) multiply(half, half) 
               else multiply(multiply(half, half), matrix)
    }
    
    val matrix = arrayOf(intArrayOf(1, 1), intArrayOf(1, 0))
    val result = power(matrix, n - 1)
    return result[0][0]
}

2. 状态压缩的DP

// 使用滚动数组优化空间复杂度
fun optimizedKnapsack(weights: IntArray, values: IntArray, capacity: Int): Int {
    val dp = IntArray(capacity + 1)
    
    for (i in weights.indices) {
        for (w in capacity downTo weights[i]) {
            dp[w] = maxOf(dp[w], dp[w - weights[i]] + values[i])
        }
    }
    return dp[capacity]
}

安卓特有优化

1. 视图查找优化

// 使用缓存优化视图查找
fun findViewsWithType(root: View, type: Class<*>): List<View> {
    val result = mutableListOf<View>()
    val cache = mutableMapOf<Class<*>, Boolean>()
    
    fun isInstanceOf(view: View, clazz: Class<*>): Boolean {
        return cache.getOrPut(clazz) { clazz.isInstance(view) }
    }
    
    fun traverse(view: View) {
        if (isInstanceOf(view, type)) {
            result.add(view)
        }
        if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                traverse(view.getChildAt(i))
            }
        }
    }
    
    traverse(root)
    return result
}

2. 高效的防抖节流

// 结合防抖和节流的最佳实践
fun optimizedThrottle(
    delay: Long,
    leading: Boolean = false,
    trailing: Boolean = true,
    action: () -> Unit
): () -> Unit {
    var lastCallTime = 0L
    var timer: Job? = null
    
    return {
        val currentTime = System.currentTimeMillis()
        val elapsed = currentTime - lastCallTime
        
        if (elapsed >= delay) {
            if (leading) {
                action()
                lastCallTime = currentTime
            } else {
                timer?.cancel()
                timer = CoroutineScope(Dispatchers.Main).launch {
                    delay(delay)
                    if (trailing) {
                        action()
                        lastCallTime = System.currentTimeMillis()
                    }
                }
            }
        } else {
            timer?.cancel()
            timer = CoroutineScope(Dispatchers.Main).launch {
                delay(delay - elapsed)
                if (trailing) {
                    action()
                    lastCallTime = System.currentTimeMillis()
                }
            }
        }
    }
}

集合处理优化

1. 并行处理大数据集

// 使用协程并行处理大数据集
suspend fun parallelProcess(data: List<DataItem>): List<Result> = coroutineScope {
    data.chunked(1000) // 分批处理
        .map { chunk ->
            async(Dispatchers.Default) {
                chunk.filter { it.isValid() }
                    .map { transformItem(it) }
            }
        }
        .awaitAll()
        .flatten()
}

2. 优化的集合差异查找

// 使用哈希集优化差异查找
fun <T> optimizedFindDifferences(
    oldList: List<T>,
    newList: List<T>,
    hash: (T) -> Int = { it.hashCode()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值