09 2013 档案
摘要:Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.If the last word does not exist, return 0.Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "H
阅读全文
摘要:Given a list, rotate the list to the right by k places, where k is non-negative.For example:Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL.记住是向右移。。/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x)
阅读全文
摘要:Given a set of distinct integers, S, return all possible subsets.Note:Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets.For example,If S = [1,2,3], a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]注意空集class Solution {publi...
阅读全文
摘要:Givennnon-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.For example,Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.用一个栈辅助,小于等于栈顶的话压入,大于栈顶就把所有小于当前值的元素出栈,计算面积面积也用一个栈,每次把新的面积覆盖范围内的所有的面积出栈,剩下到最后的就是相互独立的了将这些面积加起来,并且减去下面的
阅读全文
摘要:转自 http://www.cnblogs.com/goodhacker/archive/2011/07/20/2111996.htmlC风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:TYPE b = (TYPE)a。C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。const_cast,字面上理解就是去const属性。static_cast,命名上理解是静态类型转换。如int转换成char。dynamic_cast,命名上理解是动态类型转换。如子类和父类之间的多态类型转换。reinterpret_cast,仅仅重新解释类型,但没有进行二进制的转换。
阅读全文
摘要:Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.Each number in C may only be used once in the combination.Note:All numbers (including target) will be positive integers.Elements in a combination (a1, a2, … ,
阅读全文
摘要:Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.The same repeated number may be chosen from C unlimited number of times.Note:All numbers (including target) will be positive integers.Elements in a combination (a1, a
阅读全文
摘要:Reading Phone Number#include#include#include#include#include#include#include#include#define _USE_MATH_DEFINES#includeusing namespace std;string Sub(char val,int count){ if(count==0)return ""; string pre,after; bool sep=false; switch(count){ case 1: pre=""; break; case...
阅读全文
摘要:The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...1 is read off as "one 1" or 11.11 is read off as "two 1s" or 21.21 is read off as "one 2, then one 1" or 1211.Given an integer n, generate the nth sequence.Note: The
阅读全文
摘要:Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root).For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its bottom-up level order traversal as:[ [15,7] [9,20], [3],]conf...
阅读全文
摘要:Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its level order traversal as:[ [3], [9,20], [15,7]]confused what"{1,#,2,3}"means?> read more .
阅读全文
摘要:Given a binary tree, return theinordertraversal of its nodes' values.For example:Given binary tree{1,#,2,3}, 1 \ 2 / 3return[1,3,2].Note:Recursive solution is trivial, could you do it iteratively?confused what"{1,#,2,3}"means?> read more on how binary tree is serialized on OJ.OJ'
阅读全文
摘要:Given a strings1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.Below is one possible representation ofs1="great": great / \ gr eat / \ / \g r e at / \ a tTo scramble the string, we may choose any non-leaf no...
阅读全文
摘要:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node./** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x...
阅读全文
摘要:Implement strStr().Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.实现KMPclass Solution {public: char *strStr(char *haystack, char *needle) { // Start typing your C/C++ solution below // DO NOT write int main() function ...
阅读全文
摘要:A message containing letters from A-Z is being encoded to numbers using the following mapping:'A' -> 1'B' -> 2...'Z' -> 26Given an encoded message containing digits, determine the total number of ways to decode it. For example,Given encoded message "12",it
阅读全文
摘要:Given a collection of integers that might contain duplicates, S, return all possible subsets.Note:Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets.For example,If S = [1,2,2], a solution is:[ [2], [1], [1,2,2], [2,2], [1,2], []]普通遍历class S...
阅读全文
摘要:Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4,return 1->4->3->2->5->NULL.Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ length of list./** * Definition for singly-linked li
阅读全文
摘要:Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.Note: You can only move either down or right at any point in time.对mxn的格子扫一遍,每个格子的值等于上方和左方格子值中较小的class Solution {public: int minPathSum(vector > &am
阅读全文
摘要:Given a binary tree, determine if it is a valid binary search tree (BST).Assume a BST is defined as follows:The left subtree of a node contains only nodes with keys less than the node's key.The right subtree of a node contains only nodes with keys greater than the node's key.Both the left an
阅读全文
摘要:Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?confused what "{1,#,2,3}" means? > read more on how binary tree is se
阅读全文
摘要:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]&qu
阅读全文
摘要:Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.For example, given n = 3, a solution set is:"((()))", "(()())", "(())()", "()(())", "()()()"很简单的递归实现class Solution {public: void Sub(vector* ret,st
阅读全文
摘要:Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.Note:Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)The solution set must not contai
阅读全文
摘要:Given a digit string, return all possible letter combinations that the number could represent.A mapping of digit to letters (just like on the telephone buttons) is given below.Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", &q
阅读全文
摘要:Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note:You are not suppose to use th
阅读全文
摘要:Memset的原型是void *memset(void *s, char ch, size_t n);Memset是按字节赋值的,对char以外的类型赋0(00000000) -1(11111111)以外的值
阅读全文
摘要:Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome.Note:Have you consider that the string might be empty? This is a good questi
阅读全文
摘要:Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.Your algorithm should run in O(n) complexity.unordered_set是C++自带的hash表class Solu
阅读全文
摘要:C++Memset误区C++ 哈希表C++类型转换[转]C++ sizeofC++ 路径中\\与/
阅读全文
摘要:从2011年开始,C++支持非排序的unordered_map和unordered_set(原先的map和set都是通过有序结构实现的)下面是一些性能上的测试#include#include#include#include#include#include#include#includeusing namespace std;int main(){ int n=100000; vector vec; srand(unsigned(time(0))); for(int i=0;i tm; unordered_sethm; start=clock(); for(int i=0;i#include#i
阅读全文
摘要:Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.An example is the root-to-leaf path 1->2->3 which represents the number 123.Find the total sum of all root-to-leaf numbers.For example, 1 / \ 2 3 The root-to-leaf path 1->2 represents the nu
阅读全文
摘要:Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:Only one letter can be changed at a timeEach intermediate word must exist in the dictionaryFor example, Given:start = "hit"end = "cog"dict = ["hot&quo
阅读全文
摘要:Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:Only one letter can be changed at a timeEach intermediate word must exist in the dictionaryFor example, Given:start = "hit"end = "cog"dict = ["
阅读全文
摘要:Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.You may assume no duplicates in the array. Here are few examples.[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0class Solution {p
阅读全文
摘要:Given a sorted array of integers, find the starting and ending position of a given target value.Your algorithm's runtime complexity must be in the order of O(log n).If the target is not found in the array, return [-1, -1]. For example,Given [5, 7, 7, 8, 8, 10] and target value 8,return [3, 4].cl
阅读全文
摘要:Write a function to find the longest common prefix string amongst an array of strings.class Solution {public: string longestCommonPrefix(vector &strs) { // Start typing your C/C++ solution below // DO NOT write int main() function if(strs.size()==0)return ""; int minSi...
阅读全文
摘要:Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.You may not alter the values in the nodes, only nodes itself may be changed.Only constant memory is all
阅读全文
摘要:Given a linked list, swap every two adjacent nodes and return its head. For example,Given 1->2->3->4, you should return the list as 2->1->4->3.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed./** * Definition
阅读全文
摘要:Follow up for problem "Populating Next Right Pointers in Each Node".What if the given tree could be any binary tree? Would your previous solution still work?Note:You may only use constant extra space. For example,Given the following binary tree, 1 / \ 2 3 / \ \ 4 5...
阅读全文
摘要:Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.Initially, all next pointers are set to NULL...
阅读全文
摘要: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 function to determine if a given target is in the array.class Solution {public: bool search(int A[], int n, int target) { if(n==0)return false; ...
阅读全文
摘要: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 value to search. If found in the array return its index, otherwise return -1.You may assume no duplicate exists in the array.class Solution {public: in...
阅读全文
摘要:Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return[ [5,4,11,...
阅读全文
摘要:Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ ...
阅读全文
摘要:Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => true"abc" => false"1 a" => false"2e10" => trueNote: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before
阅读全文
摘要: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.class Solution {public: int firstMissingPositive(int A[], int n) { // Start typing your C/C++ solutio
阅读全文
摘要:Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \3 4 4 3 But the following is not: 1 / \ 2 2 \ \ 3 3 Note:Bonus points if you could solve it both recursively and itera...
阅读全文
摘要:Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value./** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * ...
阅读全文
摘要:Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node./** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x...
阅读全文
摘要:Determine whether an integer is a palindrome. Do this without extra space.click to show spoilers.Some hints:Could negative integers be palindromes? (ie, -1)If you are thinking of converting the integer to string, note the restriction of using extra space.You could also try reversing an integer. Howe
阅读全文
摘要:The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)P A H NA P L S I I GY I RAnd then read line by line: "PAHNAPLSIIGYIR"Write the code that will take a string
阅读全文
摘要:There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).class Solution {public: int FindKthElm(int A[],int bA,int eA,int B[],int bB,int eB,int k){ if(bA>eA){ return B[bB+k-...
阅读全文
摘要:Given an array where elements are sorted in ascending order, convert it to a height balanced BST./** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: ...
阅读全文
摘要:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST./** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for binary tree * struc...
阅读全文
摘要:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity./** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *mergeKLists(ve...
阅读全文
摘要:Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.class Solution {public: void merge(int A[], int m, int B[], int n) {...
阅读全文
摘要:iven a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.For example, given the following triangle[ [2], [3,4], [6,5,7], [4,1,8,3]]The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point i...
阅读全文
摘要:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists./** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class So...
阅读全文
摘要:Given an array of integers, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two nu...
阅读全文
摘要:Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.简
阅读全文
摘要:Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.通过动归,每次i,j终点的串是回文需要s[i]==s[j]且i+1,j-1串是回文class Solution {public: string longestPalindrome(string s) { // Start typin...
阅读全文
摘要:You are given an n x n 2D matrix representing an image.Rotate the image by 90 degrees (clockwise).Follow up: Could you do this in-place?class Solution {public: void rotate(vector > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int n=...
阅读全文
摘要:The n-queens puzzle is the problem of placing n queens on an n�n chessboard such that no two queens attack each other.Given an integer n, return all distinct solutions to the n-queens puzzle.Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and &
阅读全文
摘要:Implement int sqrt(int x).Compute and return the square root of x.二分搜索法class Solution {public: int sqrt(int x) { // Start typing your C/C++ solution below // DO NOT write int main() function if(xx){ end=mid-1; } else{ if(a+m...
阅读全文
摘要:Given a number represented as an array of digits, plus one to the number.class Solution {public: vector plusOne(vector &digits) { // Start typing your C/C++ solution below // DO NOT write int main() function bool carry=true; vector ret; ret.resize(digits.size())...
阅读全文
摘要:Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.class Solution {public: string intToRoman(int num) { string ret; while(num>999){ ret.append("M"); num-=1000; } if(num>899){ ret.ap...
阅读全文
摘要:Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.class Solution {public: int romanToInt(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int lastValue=0; int value; ...
阅读全文
摘要:Implementatoito convert a string to an integer.Hint:Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.Notes:It is intended for this problem to be specified vaguely (ie, no given input specs). You are respo
阅读全文
摘要:Reverse digits of an integer.Example1:x = 123, return 321Example2:x = -123, return -321Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer's last digit is 0, what should the output be? ie, cas
阅读全文
浙公网安备 33010602011771号