leetcode题解


[leetcode] First Missing Positive

First Missing Positive Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. 关键是只允许常数空间。这里要突破思维定势,要改变给定数组的结构。 对于A[i],如果A[i] > 0 && A[i] <= n,则将它与A[i] – 1 位置的元素互换位置。 遍历一遍后,再从左到右找到第一个A[i] != i + […]


[leetcode] Multiply Strings

Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. Tags: math, string 字符串相乘,关键是模拟我们平时手算乘法时的过程。取出num2的每一位,乘以num1,再把之前得到的re向左移一位,再加上这个循环中的结果。所以我们需要实现两个函数multiplyNum(字符串乘以数字)和sum(两个字符串相加)。 num1或num2为零需要单独考虑,否则结果会出现类似0000的情况。 class Solution { public: string multiply(string num1, string num2) { int i = 0; string re; if(num1 == “0” […]


[leetcode] Combinations

Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 … n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] tag: backtracking 回溯问题,用递归求解就好。 class Solution { public: vector<vector<int> > combine(int […]