leetcode 中等题(1)
2. Add Two Numbers(中等)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* first = l1;
ListNode* second = l2;
int result1=,result2=;
long long result=;
stack<int> S;
int count=; while(l1 != NULL){
S.push(l1->val);
l1 = l1->next;
} count = S.size()-;
while(!S.empty()){
result1 += pow(,count--) * S.top();
S.pop();
} while(l2 != NULL){
S.push(l2->val);
l2 = l2->next;
} count = S.size()-;
while(!S.empty()){
result2 += pow(,count--) * S.top();
S.pop();
} result = result1 + result2;
delete first,second; // ListNode*p = new ListNode(-1); //头节点
ListNode* pHead = NULL;
ListNode* p = pHead; if(!result){
ListNode* q = new ListNode();
pHead = q;
}
while(result){
int val = result % ;
result /= ; ListNode* q = new ListNode(val);
if(pHead == NULL){
pHead = q;
p = q;
}
else{
p->next = q;
p = p->next;
}
}
return pHead;
}
};
此方法会溢出,超过long long 型范围
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { //正确解法,按位相加,注意进位
ListNode *head = NULL, *prev = NULL;
int carry = ;
while (l1 || l2) {
int v1 = l1? l1->val: ;
int v2 = l2? l2->val: ;
int tmp = v1 + v2 + carry;
carry = tmp / ;
int val = tmp % ;
ListNode* cur = new ListNode(val);
if (!head) head = cur;
if (prev) prev->next = cur;
prev = cur;
l1 = l1? l1->next: NULL;
l2 = l2? l2->next: NULL;
}
if (carry > ) {
ListNode* l = new ListNode(carry);
prev->next = l;
}
return head;
}
3, Longest Substring Without Repeating Characters.(很慢)
int lengthOfLongestSubstring(string s) { int maxLength = ;
int count;
for(int i=;i<s.length();i++){
string currString = "";
count = ;
for(int j=i;j<s.length();j++){
if(currString.find(s[j])>=currString.length()){
currString += s[j];
count++;
cout<<s[j]<<endl;
cout<<"string:"<<currString<<endl;
if(count>maxLength) maxLength = count;
}
else{
break;
}
}
}
return maxLength;
}
5, Longest Palindromic Substring.(很慢)
string longestPalindrome(string s) {
string maxString = "";
int maxLength = ;
int count = ; for(int i=;i<s.length();i++){
string Str = "";
int index = s.rfind(s[i]);
int start = i;
int end = index;
int count = ;
int ii=start; while(ii<=index){
if(s[ii]==s[index]){ii++;index--;}
else{
ii = start;
index = end-;
end--;
} //匹配失败
} if(ii>index){ //匹配成功
for(int k=start;k<=end;k++)
Str += s[k];
count = Str.length();
}
if(count>=maxLength) {maxString = Str;maxLength=count;}
}
return maxString;
}
8. String to Integer (atoi)(中等,参考)
int myAtoi(string str) {
long result = ;
int indicator = ;
for(int i = ; i<str.size();)
{
i = str.find_first_not_of(' ');
if(str[i] == '-' || str[i] == '+')
indicator = (str[i++] == '-')? - : ;
while(''<= str[i] && str[i] <= '')
{
result = result* + (str[i++]-'');
if(result*indicator >= INT_MAX) return INT_MAX;
if(result*indicator <= INT_MIN) return INT_MIN;
}
return result*indicator;
}
return ;
}
15,3Sum(中等)
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int sum;
sort(nums.begin(),nums.end());
for(int i=;i<nums.size();i++){
if(i> && nums[i]==nums[i-])
continue;
int l=i+;
int r=nums.size()-; while(l<r){
sum = nums[i]+nums[l]+nums[r];
if(sum<) l++;
else if(sum>) r--;
else{
res.push_back(vector<int>{nums[i],nums[l],nums[r]});
while(nums[l]==nums[l+]) l++; //去除重复
while(nums[r]==nums[r-]) r--;
l++;
r--;
}
} }
return res;
}
11. Container With Most Water(很慢)
int maxArea(vector<int>& height) {
int maxAreas=;
int currAreas=;
for(int i=;i<height.size();i++){
for(int j=i+;j<height.size();j++){
currAreas = (j-i)*min(height[i],height[j]);
if(currAreas>maxAreas) maxAreas = currAreas;
}
}
return maxAreas;
}
12. Integer to Roman(中等)
string intToRoman(int num) {
const string THOUS[]={"","M","MM","MMM"};
const string HUNDS[]= {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
const string TENS[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
const string ONES[]={"","I","II","III","IV","V","VI","VII","VIII","IX"}; string result = "";
result += THOUS[num/]; num %= ;
result += HUNDS[num/]; num %= ;
result += TENS[num/]; num %= ;
result += ONES[num%]; return result;
}
16. 3Sum Closest(较快)
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int minDist=INT_MAX;
int res=;
for(int i=;i<nums.size();i++){
int l=i+;
int r=nums.size()-;
while(l<r){
int sum = nums[i]+nums[r]+nums[l];
if(sum==target) return sum;
if(abs(sum-target)<minDist) {res=sum;minDist=abs(sum-target);}
if(sum>target) r--;
else l++;
}//while
}
return res;
}
};
17. Letter Combinations of a Phone Number(较快)
vector<string> letterCombinations(string digits) {
if(digits.empty()) return vector<string>();
vector<string> result;
result.push_back("");
vector<string> src = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for(int i=;i<digits.size();i++){
int num = digits[i]-'';
if(num< || num>) break;
const string& candidate = src[num];
if(candidate.empty()) continue;
vector<string> tmp;
for(int j=;j<candidate.size();j++){
for(int k=;k<result.size();k++)
tmp.push_back(result[k]+candidate[j]);
}
result.swap(tmp);
}
return result;
}
19. Remove Nth Node From End of List(中等)
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL) return NULL;
ListNode* after=head;
ListNode* befor=head;
ListNode* toBeDelete; for(int i=;i<n;i++){
befor = befor->next;
if(befor==NULL) return head->next;
} while(befor->next!=NULL){
befor = befor->next;
after = after->next;
} toBeDelete = after->next;
after->next = toBeDelete->next;
delete toBeDelete;
toBeDelete = NULL; return head;
}
22. Generate Parentheses(中等)
vector<string> res;
void helper(string str,int left,int right){
if(left== && right==) res.push_back(str);
if(left!=) helper(str+'(',left-,right);
if(right!= && right>left) helper(str+')',left,right-);
} vector<string> generateParenthesis(int n) {
helper("",n,n);
return res;
}
24. Swap Nodes in Pairs(较快)
ListNode* swapPairs(ListNode* head) {
if(head==NULL) return NULL;
ListNode tmp();
ListNode* curr=head;
ListNode* pre=&tmp;
tmp.next=head; while(curr && curr->next){
pre->next=curr->next;
pre=pre->next;
curr->next=pre->next;
pre->next=curr;
pre=curr;
curr=curr->next;
}
return tmp.next;
}
leetcode 中等题(1)的更多相关文章
- leetcode 中等题(2)
50. Pow(x, n) (中等) double myPow(double x, int n) { ; unsigned long long p; ) { p = -n; x = / x; } el ...
- LeetCode中等题(三)
题目一: 反转从位置 m 到 n 的链表.请使用一趟扫描完成反转. 说明:1 ≤ m ≤ n ≤ 链表长度. 示例: 输入: 1->2->3->4->5->NULL, m ...
- LeetCode中等题(一)
题目一: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表 ...
- leetcode中等题
# Title Solution Acceptance Difficulty Frequency 1 Two Sum 44.5% Easy 2 Add Two Number ...
- LeetCode中等题(二)
题目一: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复 ...
- 这样leetcode简单题都更完了
这样leetcode简单题都更完了,作为水题王的我开始要更新leetcode中等题和难题了,有些挖了很久的坑也将在在这个阶段一一揭晓,接下来的算法性更强,我就要开始分专题更新题目,而不是再以我的A题顺 ...
- LeetCode刷题笔记和想法(C++)
主要用于记录在LeetCode刷题的过程中学习到的一些思想和自己的想法,希望通过leetcode提升自己的编程素养 :p 高效leetcode刷题小诀窍(这只是目前对我自己而言的小方法,之后会根据自己 ...
- leetcode刷题指南
转载自:http://blog.csdn.net/lnho2015/article/details/50962989 以下是我个人做题过程中的一些体会: 1. LeetCode的题库越来越大,截止到目 ...
- LeetCode刷题总结-数组篇(上)
数组是算法中最常用的一种数据结构,也是面试中最常考的考点.在LeetCode题库中,标记为数组类型的习题到目前为止,已累计到了202题.然而,这202道习题并不是每道题只标记为数组一个考点,大部分习题 ...
随机推荐
- Hibernate架构
参照: http://blog.csdn.net/lovesummerforever/article/details/19169779 http://www.w3cschool.cn/hibernat ...
- 12. ajax、datagrid请求传参实例
############实例1:############ var data = {};data.orgRoleCode = orgRoleCode;data.orgRoleName = orgRole ...
- 转载:approxPolyDP函数
本文转载http://blog.csdn.net/qq_18343569/article/details/47999257 1.approxPolyDP函数 函数的作用: 对图像轮廓点进行多边形拟合 ...
- Linux 实现与宿主机共享文件夹 Centos7
(选用的系统 centos7) 01,添加共享目录,右键虚拟机 => 设置 => 选项 => 共享文件夹(只有在虚拟机为关机状态才能添加) 02,开机,查看当前虚拟机的共享目录 =& ...
- poi excel设置合并单元格边框格式
版本3.17 //设置合并单元格的边框 public static void setBorderForMergeCell(BorderStyle style,int color, CellRangeA ...
- crontab 安装与配置
安装方法: yum -y install vixie-cron yum -y install crontabs 说明:vixie-cron 软件包是 cron 的主程序:crontabs 软件包是用来 ...
- APP-2.1-Hbuilder与夜神 & HbuilderX与夜神模拟器连接
经上一步完成Hbuilder.HbuilderX与夜神模拟器的安装,本次介绍下两者之间的连接设置. 1.三者的安装路径 Hbuilder:E:\SAP UI5\HBuilder HbuilderX:D ...
- python redis客户端使用lua脚本
有一个需求,为一个key设置一个field存储时间戳,每当有新数据,判断新数据时间戳是否大于之前的时间戳,如果是,更新时间戳,由于依赖中间执行结果,所以使用lua减少客户端和服务端通信次数. #!/u ...
- U3D 编辑器中sceneview下相机操作相关
前几天在项目中想要实现一个编辑器模式下的3D空间画线功能,几经周折,还是作废. 原因有:相机空间到世界空间转换问题对于Z值不清楚,U3D自定义坐标轴控制问题,射线与平面求交点不对, 一个关键问题是:编 ...
- NETIF_F_LLTX 的属性
在bond初始化的时候,我们可以看到如下属性: /* don't acquire bond device's netif_tx_lock when transmitting */ bond_d ...