这里解决leetcode的两道题,第1题(twosum)和第202题(happy number)
因为这里要使用hash的思想,首先回顾下hash表的定义。
哈希表其实又叫散列表,是算法在时间和空间上做出权衡的经典例子。如果一个表所有的键都是小整数,我们就可以用一个数组来实现无序的符号表,将键作为数组的索引而数组中i出存储的值就是它对应的值。
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
一般思想就是通过暴力方法求出,固定一个元素,再遍历剩下的元素,这种方法的复杂度是O(n^2)。
而用hash表的思想就是把元素值当做键,元素位置索引当做值,使得所有的元素存入了一个hash表,然后我们只需要遍历一次表就可以得出答案,此时复杂度是O(n)。
这里列出完整代码:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> m;
vector<int> v;
//把所有元素加入到hash map中
//键为元素值,值为元素位置索引(从0开始)
for (int i=0; i<nums.size(); i++) {
m[nums[i]] = i;
}
for (int i=0; i<nums.size(); i++) {
//第一个条件:如果m中没有等于target-nums[i]的元素,返回的迭代器等于end函数返回的迭代器
//第二个条件:元素位置小于对应元素的位置
if(m.find(target - nums[i])!=m.end()&&i<m[target - nums[i]]){
//把当前位置索引加入到v
v.push_back(i);
//把target-当前位置的位置索引加入加入到v
v.push_back(m[target - nums[i]]);
break;
}
}
return v;
}
int main(int argc, const char * argv[]) {
int a[4]={2,7,11,15};
vector<int> arr(a,a+4);
vector<int> index;
int target=9;
index=twoSum(arr,target);
cout<<index[0]<<index[1]<<endl;
return 0;
}
2.happy number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:
思想:将每次计算的平方和在hash表中寻找是否有相同的,如果有,就说明不是快乐数;如果没有就再次计算平方和,直到结果1,说明是快乐数。
完整代码:
#include <iostream>
#include <set>
#include <cmath>
using namespace std;
int SUM(int n){
int sum=0;
while (n) {
sum += pow((n%10),2);
n = n/10;
}
return sum;
}
bool isHappy(int n) {
set<int> s;
int sum = SUM(n);
while (sum!=1) {
//如果在s中没有找到sum这个值,就添加到s中,接着计算SUM
if (s.find(sum)==s.end()) {
s.insert(sum);
sum = SUM(sum);
}
//如果在s中存在sum这个值,就说明不是快乐数
else{
return false;
}
}
//如果sum==1,说明是快乐数
return true;
}
int main(int argc, const char * argv[]) {
int num = 19;
int re=isHappy(num);
cout<<re<<endl;
return 0;
}