LeetCode 1. Two Sum

本文提供了一种解决LeetCode经典问题“两数之和”的高效算法。该算法通过将原始数组转换为带有索引的节点,并利用动态数组进行排序,进而采用双指针策略寻找目标和。这种方法避免了暴力枚举的高时间复杂度。

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.
在这里插入图片描述
题解:
最开始想到的还是暴力枚举,但由于昨天复习的数据结构里说到降低时间复杂度,首先我便想到了使用map排序,但调试过程中发现其实里面的元素是有重复的,便放弃了这种想法。后来想到用节点存储值和下标,利用动态数组储存结点并对值进行排序,再定义i,j来分别首尾遍历,若是对应的两个值不等于target,判断大于还是小于,若是大于,j–;小于,i++。
直到找到相等并存入ans动态数组里。
代码:

class Solution {
public:
    struct node{
        int value;
        int index;
    };
    static int  cmp(node a,node b){
        return a.value<b.value;
    }
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<node> v;
        for(int i=0;i<nums.size();i++){
            v.push_back({nums[i],i});
        }
        sort(v.begin(),v.end(),cmp);
        int i=0,j=v.size()-1;
        vector<int> ans;
        while(i!=j){
            if(v[i].value+v[j].value==target){
                ans.push_back(v[i].index);
                ans.push_back(v[j].index);
                break;
            }
            else if(v[i].value+v[j].value<target){
                i++;
            }
            else j--;
        }
        return ans;
    }
};

在这里插入图片描述
因为以前没有再leetcode上做过题,所以不太熟悉leetcode的在线编程方式,费了很多时间,但也学到了很多东西,又是一点点进步呀~ 加油~
在leetcode里cmp函数前面是用static int,标准用法,用bool编译器无法通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值