LeedCode-Two Sum

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.

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
         int[] sumnumbers =new int[2];
        
        for (int i = 0; i <= nums.Length-1; i++)
        {
            for (int j = 0; j <= nums.Length-1; j++)
            {
                if (nums[i] + nums[j] - target == 0 && i != j)
                {
                    if (i < j)
                    {
                        sumnumbers[0] = i;
                        sumnumbers[1] = j;
                        return sumnumbers;
                    }
                    else
                    {
                        sumnumbers[0] =j;
                        sumnumbers[1] = i;
                        return sumnumbers;
                    }
                }
                  
            }
        }
        return sumnumbers;
    }
}

Top sulution 【O(n)】 C++的top解决方案

vector<int> twoSum(vector<int> &numbers, int target)
{
    //Key is the number and value is its index in the vector.
    unordered_map<int, int> hash;
    vector<int> result;
    for (int i = 0; i < numbers.size(); i++) {
        int numberToFind = target - numbers[i];

            //if numberToFind is found in map, return them
        if (hash.find(numberToFind) != hash.end()) {
                    //+1 because indices are NOT zero based
            result.push_back(hash[numberToFind] + 1);
            result.push_back(i + 1);            
            return result;
        }

            //number was not found. Put it in the map.
        hash[numbers[i]] = i;
    }
    return result;
}

 C#的仿写

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
    int[] RetIndecis = {0,0};
    Hashtable hsNums = new Hashtable();
    hsNums.Clear();
    //i is the latter index
    for(int i=0;i<nums.Length;i++)
    {
        int targetKey = target - nums[i];
        //if targetKey exist
        if(hsNums.ContainsKey(targetKey))
        {
            RetIndecis[1] = i + 1;
            RetIndecis[0] = (int)hsNums[targetKey];
            return RetIndecis;
        }
        //key is the number and value is the index,filter the number which has existed
        if(!hsNums.ContainsKey(nums[i]))
            hsNums.Add(nums[i],i + 1);
    }
    return(RetIndecis);
}
}

 

 

posted @ 2016-12-16 15:01  carsonche  阅读(245)  评论(0编辑  收藏  举报