先看看这个题目:某整形数组中除了两个单身整数外, 其余的整数都是成对出现的, 利用C代码求出这两个单身整数. 要求: 时间复杂度o(n), 空间复杂度o(1). 我们先用最傻瓜的方式来做吧: #include <iostream> using namespace std; // 时间复杂度为o(n^2), 空间复杂度为o(1), 不符合要求 void findSoleNumbers(int a[], int n, int &e1, int &e2) { int i = 0; i
(1).把输入规模看成x轴,所花时间/空间看成y轴 O(n)就是y=x,y随x的增长而线性增长.也就是成正比,一条斜线. O(1)就是y=1,是一个常量,不管x怎么变,y不变,一条与x轴平行的线. (2).举个简单的例子,要从0加到n,我们会这么写: int sum = 0; for(int i = 0;i<=n;++i) { sum + = i; } 一共算了n次加法,那么就说这个时间复杂度是O(n).当然O(n)的精确的概念是,是n的最高次方,比如,某个计算共计算了3n+2次,那么这个时间复
//时间复杂度O(n),空间复杂度O(n) void findSequence(int* arr, int len) { int* hashtable = new int[RANGE]; memset(hashtable, 0, RANGE); for (int i = 0; i < len; ++i) { hashtable[arr[i]] = 1; } cout << "(a,b): "; for (int i = 0; i < len; ++i) { if
引言 一维动态规划根据转移方程,复杂度一般有两种情况. func(i) 只和 func(i-1)有关,时间复杂度是O(n),这种情况下空间复杂度往往可以优化为O(1) func(i) 和 func(1~i-1)有关,时间复杂度是O(n*n),这种情况下空间复杂度一般无法优化,依然为O(n) 本篇讨论第一种情况 例题 1 Jump Game Given an array of non-negative integers, you are initially positioned at the fi
一.栈的介绍: 1)栈的英文为(stack)2)栈是一个先入后出(FILO-First In Last Out)的有序列表.3)栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表.允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom).4)根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除 5)出栈(pop)和入栈(push)的概念 栈
刷题备忘录,for bug-free leetcode 396. Rotate Function 题意: Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: F(k
由于之前对算法题接触不多,因此暂时只做easy和medium难度的题. 看完了<算法(第四版)>后重新开始刷LeetCode了,这次决定按topic来刷题,有一个大致的方向.有些题不止包含在一个topic中,就以我自己做的先后顺序为准了. Array ---11.Container With Most Water 给定许多条与y轴平行的直线,求其中两条直线与x轴围成的容器的最大容量. 这道题用到了双指针的思想.我们在数轴的两端分别放置一个left指针和right指针,因为容器容量=较短边*两边
Description: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example,Given nums = [0, 1, 3] return 2. Note:Your algorithm should run in linear runtime complexity. Could you imp