Commit 9789e8f5 by 李楚霏

每日刷题

parent 5c9ccb7e
/**
* 一次哈希遍历
* 解题思路:数值作为map的键,下标作为map的值;
* 每次遍历时,如果target-nums[i]在map中能找到值,
* 说明target的两个数已经找到,就返回
*/
#include <iostream>
#include<vector>
#include<map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>res;
map<int, int> hashmap;
for(int i=0; i< nums.size();i++) {
if(hashmap[target-nums[i]] && hashmap[target-nums[i]] != i+1) {
res.push_back(i);
res.push_back(hashmap[target-nums[i]]-1);
return res;
}
//不让hash的下标为负
hashmap[nums[i]] = i+1;
}
return res;
}
};
int main() {
Solution s;
vector<int> test= {-2,11, 4, 15, 7,5};
for(int i =0; i< s.twoSum(test, 9).size();i++) {
cout<< s.twoSum(test, 9)[i]<<endl;
}
return 0;
}
\ No newline at end of file
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let hashMap = {};
for(let i=0; i < nums.length;i++) {
let n = target -nums[i];
let find = hashMap[n];
if (find!= undefined) return hashMap[find,i];
else hashMap[nums[i]] = i;
}
};
let nums = [2,7,11,15];
let target = 9;
twoSum(nums, target);
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* next = NULL;
// 错误原因:递归不需要什么循环,因为递归本身就是循环
// while(head!= NULL && head->next != NULL) {
next= head->next;
head->next = swapPairs(next->next);
next->next = head;
// }
return next;
}
};
int main() {
ListNode* head = new ListNode(1);
ListNode* head1 = new ListNode(2);
ListNode* head2 = new ListNode(3);
ListNode* head3 = new ListNode(4);
head->next =head1;
head1->next =head2;
head2->next =head3;
Solution s;
s.swapPairs(head);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment