首页 > 其他 > 详细

Leetcode1 - 10

时间:2020-11-23 15:18:37      阅读:23      评论:0      收藏:0      [点我收藏+]

 

1. 两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> v;
        for(int i = 0;i < nums.size();i++){
            for(int j = i;j < nums.size();j++){
                if(i != j && nums[i] + nums[j] == target){
                    v.push_back(i);
                    v.push_back(j);
                }
            }
        }
        return v;
    }
};

4. 寻找两个正序数组的中位数

思路:

  1. 将两个数组中的值分别放入数组一个新的数组v中
  2. 然后新的数组进行排序
  3. 最后根据排序好的数组算出中位数
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<int> v;
        for(int i = 0;i < nums1.size();i++){
            v.push_back(nums1[i]);
        }
        for(int i = 0;i < nums2.size();i++){
            v.push_back(nums2[i]);
        }
        sort(v.begin(),v.end());
        if(v.size() % 2 == 1)
            return v[v.size() / 2];
        else
            return (v[v.size() / 2] + v[v.size() / 2 - 1])/2.0;
    }
};

7. 整数反转

class Solution {
public:

    typedef long long ll;

    int count(ll x){
        int count = 0;
        while(x){
            x /= 10;
            count++;
        }
        return count;
    }

    int reverse(int x) {
        ll ans = 0;
        int len = count(x);
        while(x){
            ans += (x % 10) * pow(10,count(x) - 1);
            x /= 10;
            len--;
        }

        if(ans > INT_MAX || ans < INT_MIN)
            return 0; 
        return (int)ans;
    }
};

9. 回文数

思路:

  1. 当数为负数时,他肯定不是一个回文数,所以直接返回false
  2. 加入不是负数,将该数的每一位放入数组中,分别进行正向遍历和反向遍历,如果不相等则直接返回false,当遍历完整个数组后,返回true
class Solution {
public:
bool isPalindrome(int x) {
    
    if(x < 0)
        return false;
    
    vector<char> v;
    while(x){
        v.push_back(x % 10);
        x /= 10;
    }
    for(int i = 0,j = v.size() - 1;i < v.size();i++,j--){
        if(v[i] != v[j])
            return false;
    }

    return true;
}
};

  

Leetcode1 - 10

原文:https://www.cnblogs.com/wsjhs/p/14023780.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!