LeetCode (A)

LeetCode (interview questions online judge) http://www.leetcode.com/onlinejudge

id: lcfr


all questions with codes will be updated here in this thread of blog.

another programmer job discussion site CareerCup is http://www.careercup.com/







3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        int n=num.size();
        map<int,int> hash;
        for(int i=0;i<n;++i)
            hash[num[i]]=hash[num[i]]+1;
        sort(num.begin(),num.end());
        set<vector<int> > res;
        for(int i=0;i<n;++i)
        {
            int x=num[i];
            hash[x]=hash[x]-1;
            for(int j=i+1;j<n;++j)
            {
                int y=num[j];
                int z=0-x-y;
                if(z<y)
                    break;
                hash[y]=hash[y]-1;
                if(hash[z]>0)
                {
                    vector<int> v;
                    v.push_back(x);
                    v.push_back(y);
                    v.push_back(z);
                    res.insert(v);
                }
                hash[y]=hash[y]+1;
            }
            hash[x]=hash[x]+1;
        }
        return vector<vector<int> >(res.begin(),res.end());
    }
};









3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(),num.end());
        int n=num.size(),ans=INT_MAX,diff=INT_MAX;
        for(int i=0;i<n;++i)
        {
            for(int j=i+1;j<n;++j)
            {
                int k=j+1,old=INT_MAX;
                while(k<n)
                {
                    int sum=num[i]+num[j]+num[k];
                    int tmp=abs(sum-target);
                    if(tmp<diff)
                    {
                        diff=tmp;
                        ans=sum;
                    }
                    else if(tmp>old)
                        break;
                    old=tmp;
                    k++;
                }
            }
        }
        return ans;
    }
};









4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int n=num.size(),tmp=0;
        sort(num.begin(),num.end());
        if(target<0&&target<num[0]+num[1]+num[2]+num[3] || target>0&&target>num[n-1]+num[n-2]+num[n-3]+num[n-4])
            return vector<vector<int> >();
        if(n>0&&num[0]<0)
        {
            tmp=num[0];
            for(int i=0;i<n;++i)
                num[i]-=tmp;
            target-=4*tmp;
        }
        map<int,int> cnt;
        for(int i=0;i<n;++i)
            cnt[num[i]]=cnt[num[i]]+1;
        set<vector<int> > res;
        for(int i=0;i<n;++i)
        {
            int a=num[i];
            if(a>target)
                break;
            cnt[a]=cnt[a]-1;
            for(int j=i+1;j<n;++j)
            {
                int b=num[j];
                if(a+b>target)
                    break;
                cnt[b]=cnt[b]-1;
                for(int k=j+1;k<n;++k)
                {
                    int c=num[k];
                    int d=target-a-b-c;
                    if(d<c)
                        break;
                    cnt[c]=cnt[c]-1;
                    if(cnt[d]>0)
                    {
                        vector<int> v;
                        v.push_back(a+tmp);
                        v.push_back(b+tmp);
                        v.push_back(c+tmp);
                        v.push_back(d+tmp);
                        res.insert(v);
                    }
                    cnt[c]=cnt[c]+1;
                }
                cnt[b]=cnt[b]+1;
            }
            cnt[a]=cnt[a]+1;
        }
        return vector<vector<int> >(res.begin(),res.end());
    }
};













Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

	string addBinary(string a, string b) {
		int n = max(a.length(), b.length()) + 2;
		char *pa = new char[n];
		char *pb = new char[n];
		memset(pa, 0, n);
		memset(pb, 0, n);
		for(int i=0;i<a.length();++i)
			pa[i] = a[a.length()-1-i];
		for(int i=0;i<b.length();++i)
			pb[i] = b[b.length()-1-i];
		for(int i=0;i<n-2;++i)
		{
			pa[i] = ((pa[i]>='0')?(pa[i]-'0'):pa[i]) + ((pb[i]>='0')?(pb[i]-'0'):pb[i]);
			if(pa[i] >= 2)
				pa[i] -= 2, pa[i+1] += 1;
			pa[i] += '0';
		}
		pa[n-2] += pa[n-2]?'0':0;
		string res = string(pa);
		return string(res.rbegin(),res.rend());
	}

















Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

	ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
		ListNode *p = l1, *q = l2, *pp;
		while(p != NULL && q != NULL)
		{
			p->val += q->val;
			if(p->val >= 10)
			{
				if(p->next == NULL)
					p->next = new ListNode(1);
				else
					p->next->val += 1;
				p->val -= 10;
			}
			pp = p;
			p = p->next;
			q = q->next;
		}
		if(p == NULL)
			pp->next = q;
		else
		{
			while(p->val >= 10)
			{
				if(p->next == NULL)
					p->next = new ListNode(1);
				else
					p->next->val += 1;
				p->val -= 10;
				p = p->next;
			}
		}
		return l1;
	}















Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

class Solution {
public:
	vector<string> anagrams(vector<string> &strs) {
		map<string, string> arr;
		map<string, int> cnt;
		for(int i=0; i<strs.size(); ++i)
		{
			char *p = new char[strs[i].length()+1];
			strcpy(p,strs[i].c_str());
			sort(p,p+strlen(p));
			string str = string(p);
			arr[strs[i]] = str;
			if(cnt.find(str) == cnt.end())
				cnt[str] = 1;
			else
				++cnt[str];
		}
		vector<string> res;
		for(int i=0; i<strs.size(); ++i)
			if(cnt[arr[strs[i]]] > 1)
				res.push_back(strs[i]);
		return res;
	}
};










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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值