随笔分类 -  LeetCode

摘要:设置两个布尔数组,记录行和列是否存在0。需要注意的是如何将行或列设为0. void setZeros(vector<vector<int>> &matrix) { int m = matrix.size(); int n = matrix[0].size(); vector<bool>row(m, 阅读全文
posted @ 2016-05-16 14:21 牧马人夏峥 阅读(129) 评论(0) 推荐(0)
摘要:这题需要注意的是最后的进位 vector<int> plusOne(vector<int>& nums,int num) { add(nums, num); } void add(vector<int> &nums, int num) { int c = num; for (auto it = nu 阅读全文
posted @ 2016-05-16 13:21 牧马人夏峥 阅读(104) 评论(0) 推荐(0)
摘要:这题需要搞清楚矩阵元素的位置关系,尤其是副对角线元素,沿着副对角线元素 void rotateImage(vector<vector<int>> &matrix) { int n = matrix.size(); //沿着副对角线翻转 for (int i = 0; i < n;i++) for ( 阅读全文
posted @ 2016-05-15 20:47 牧马人夏峥 阅读(159) 评论(0) 推荐(0)
摘要:这题不太好想。可以先扫描找到最高的柱子,然后分别处理两边:记录下当前的局部最高点,如果当前点小于局部最高点,加上, 反则,替换当前点为局部最高点。 int trapWater(int A[], int n) { int peak = 0; int max = 0; int water = 0; fo 阅读全文
posted @ 2016-05-15 20:15 牧马人夏峥 阅读(348) 评论(0) 推荐(0)
摘要:判断行、列、九宫格内数字是否重复。 按照行、列、九宫格进行检查即可。 bool validSudoku(const vector<vector<char>>& board) { bool used[9]; for (int i = 0; i < 9; i++) { fill(used, used + 阅读全文
posted @ 2016-05-15 17:05 牧马人夏峥 阅读(183) 评论(0) 推荐(0)
摘要:首先是next permutation的算法的描述和分析如下: 这题一是要知道思路,编程中注意STL的用法 void nextPermutaion(vector<int> &num) { next_permutation(num.begin(), num.end()); } private: tem 阅读全文
posted @ 2016-05-15 15:34 牧马人夏峥 阅读(234) 评论(0) 推荐(0)
摘要:第一题是Two Sum 同样是用哈希表来做,需要注意的是在查打gap是要排除本身。比如target为4,有一个值为2,gap同样为2。 vector<int> twoSum(vector<int> &num, int target) { unordered_map<int, int> mapping 阅读全文
posted @ 2016-05-14 15:02 牧马人夏峥 阅读(229) 评论(0) 推荐(0)
摘要:这题要仔细体会下哈希表的用法,要注意的是数组本身是无序的,因此需要向左右进行扩张。 另外这个思路可以进行聚类,把连续的标记为一类。 int longestConsecutive(const vector<int> &num) { unordered_map<int, bool> used; for 阅读全文
posted @ 2016-05-14 14:22 牧马人夏峥 阅读(136) 评论(0) 推荐(0)
摘要:找两个排好序的数组的中间值,实际上可以扩展为寻找第k大的数组值。 参考下面的思路,非常的清晰: 代码: double findMedianofTwoSortArrays(int A[], int B[], int m, int n) { int total = m + n; //判断序列长度的奇偶, 阅读全文
posted @ 2016-05-14 13:31 牧马人夏峥 阅读(140) 评论(0) 推荐(0)
摘要:描述 Follow up for ”Search in Rotated Sorted Array”: What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a fun 阅读全文
posted @ 2016-05-01 21:34 牧马人夏峥 阅读(133) 评论(0) 推荐(0)
摘要:描述 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target 阅读全文
posted @ 2016-05-01 21:10 牧马人夏峥 阅读(134) 评论(0) 推荐(0)
摘要:描述 Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function s 阅读全文
posted @ 2016-05-01 20:30 牧马人夏峥 阅读(121) 评论(0) 推荐(0)
摘要:删除数组中的重复元素并返回新数组的个数 思路:保留不同的元素即可。 阅读全文
posted @ 2016-05-01 19:56 牧马人夏峥 阅读(117) 评论(0) 推荐(0)