DataWhale集训-1.hash,数组

这里解决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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值