Made simple using binary search


  • 0
    P

    class Solution {
    public:
    void bsearc(vector<int>& nums , vector<int>& a,int t,vector<int>& ans )
    {
    int i=0,j=a.size()-1,i1,j1;
    //int mid=i+(j-i)/2;
    vector<int>::iterator it1,it2;
    while(i<j){
    if(a[i]+a[j]==t)
    {
    for(i1=0;i1<a.size();i1++)
    {
    if(a[i]==nums[i1])
    break;
    }

        for(j1=0;j1<a.size();j1++)
        {
            if(a[j]==nums[j1]&&i1!=j1)
            break;
        }
        int tmp;
        if(i1>j1)
        {
            tmp=i1;
            i1=j1;
            j1=tmp;
        }
         ans.push_back(i1+1);
        ans.push_back(j1+1);
        return ;
    }
    if(a[i]+a[j]>t)
    {
        j--;
    }
    else
    i++;}
    

    }
    vector<int> twoSum(vector<int>& nums, int target) {
    vector<int > ans,so;
    so=nums;
    sort(so.begin(),so.end());

        bsearc(nums,so,target,ans);return ans;
    }
    

    };## Heading ##


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.