赞
踩
两数之和https://leetcode-cn.com/problems/two-sum/
- //暴力枚举
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- int n = nums.size();
- for (int i = 0; i < n; ++i) {
- for (int j = i + 1; j < n; ++j) {
- if (nums[i] + nums[j] == target) {
- return {i, j};
- }
- }
- }
- return {};
- }
- };
- //哈希表
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- unordered_map<int, int> hashtable;
- for (int i = 0; i < nums.size(); ++i) {
- auto it = hashtable.find(target - nums[i]);
- if (it != hashtable.end()) {
- return {it->second, i};
- }
- hashtable[nums[i]] = i;
- }
- return {};
- }
- };
合并两个有序链表https://leetcode-cn.com/problems/merge-two-sorted-lists/
- class Solution {
- public:
- ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
- if(list1==nullptr){
- return list2;
- }else if(list2==nullptr){
- return list1;
- }else if(list1->val < list2->val){
- list1->next = mergeTwoLists(list1->next,list2);
- return list1;
- }else{
- list2->next = mergeTwoLists(list2->next,list1);
- return list2;
- }
-
- }
- };
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
删除有序数组中的重复项https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
- class Solution {
- public:
- int removeDuplicates(vector<int>& nums) {
- int n = nums.size();
- if(n == 0){
- return 0;
- }
- int fast = 1, slow = 1;
- while(fast < n){
- if(nums[fast] !=nums[fast - 1]){
- nums[slow] = nums[fast];
- ++slow;
- }
- ++fast;
- }
- return slow;
-
- }
- };
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。