Skip to content

【问题Q&A】收集 #49

@GeekUniversity

Description

@GeekUniversity

Q: 这里的时间复杂度是 n 还是 n^2

func moveZeroes(nums []int)  {
    j:=0
    for i:=0; i<len(nums); i++{
        if nums[j] == 0 {
            // nums = append(nums[:j], append(nums[j+1:], nums[j])...)
            nums = append(nums[:j], nums[j+1:]...)
			nums = append(nums, 0)
            j--
        }
        j++
    }
}

A: 这里值得注意的是 nums = append(nums[:j], nums[j+1:]...) 这条语句, 它的作用不是 添加而是删除 下标为 j 的元素,在数组中,插入和删除元素的时间复杂度是 O(n), 由于外层 for 循环 的关系,这里的整体时间复杂度是 O(n^2)

Q: 检测环的时候使用快慢指针,走2步和走多步哪个效率高,怎么证明?

https://code-examples.net/zh-CN/q/4e4806

Q: 网上说链表和数组的插入性能都是o(n) ,这块是什么情况?

A: 数组的插入 O(n) 的复杂度毫无疑问,但是链表的插入为 O(n) 是有问题的,在这里,链表在某个点插入新的结点的时间复杂度是 O(1), 但是在找到这个位置的过程时间复杂度是 O(n), 注意把握概念。

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions