设为首页 加入收藏

TOP

C++ 算法题解
2019-06-05 02:08:13 】 浏览:94
Tags:算法 题解

1、leetcode #28 implement strStr()


题目地址:https://leetcode.com/problems/implement-strstr/


分析:实现寻找字符串的功能,即实现类似于substr()函数


      如果未找到字串,返回-1,找到返回匹配模式串的第一个字符的下标


    如果输入的匹配字符串为空,返回0


方法:KMP匹配算法


注意:当主串haystack为空时应输出-1而不是0


2. leetcode #38 count_and_say


题目地址:https://leetcode.com/problems/count-and-say/


递归


3. 题目如下图



分析:首先需要将字符串分为一个一个的单词,将分离得到的单词压入栈中


工具:#include<sstream>  #include<stack>


4.题目如下图



分析:实现字符串数字的模拟加法,考虑到一个数字字符串可能很长,比如10000个 “1”,c++中最大变量为long long int,如果单纯的将字符串转换为数字,可能会有溢出问题,故舍弃这种方法而采取模拟加法运算法----设置进位...


注意:本算法只考虑了整数的运算,未考虑到实数


 5 leetcode #75 sort colors


题目链接:https://leetcode.com/problems/sort-colors/


方法:三路快速排序法



 


 6. leetcode #167 two sum(2)


题目地址:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/


 7. leetcode #283 move_zeroes


题目地址:https://leetcode.com/problems/move-zeroes/


 8. leetcode #51 N-Queens


题目链接:https://leetcode.com/problems/n-queens/


算法分析:以4皇后为例



 9 leetcode #2 add two numbers


题目链接:https://leetcode.com/problems/add-two-numbers/


算法分析:


Method1


       if l1 and l2 are in the same size, no attention


      if l1 is longer than  l2, attention the overflow, eg. [9,9] + [1] = [0,0,1] not [0,10].


                if l2 is longer than l1,put the result of l2 to the tail of result list


Method2


     recursion


 10 leetcode # 4 median of two sorted array


题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/


算法分析:采用归并排序和堆排序。下图时采用归并排序的过程。堆排序采用一个大顶堆和小顶堆,中间值记录median。



11 leetcode # 3 longest-substring-without-repeating-characters


题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/


算法分析:



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python3 文件批量重命名操作示例 下一篇Python3实现名片管理系统示例

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目