力扣算法题——两数之和练习

题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

----------------------------------------分割线---------------------------------------------------------------------------------------

1、第一次尝试,使用暴力解题的方法,用了两个嵌套的for循环进行遍历计算

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

2、第二次尝试,将int[]数组转换成List<int>,在通过遍历int[]数组,判断List里是否存在target-i的值,如果存在取出索引值,实际运行时间增加了不少,还没搞明白为什么,回头在查查

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
       List<int> _intList = new List<int>(nums);
            for(int i = 0; i < nums.Length; i++)
            {
                if (_intList.Contains(target - nums[i]))
                {
                       if(i!= _intList.IndexOf(target - nums[i])){
                        return new int[2] { i, _intList.IndexOf(target - nums[i]) };
                    }
                }
            }
        return null;
    }
}

3、第三次尝试解题,使用哈希表,遍历一次int[]数组,每次对当前数值搜索哈希表中是否存在target-i存在,如果不存在,就把当前值存入哈希表中,直至找到解。这次代码执行效率提高了很多。

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
       int[] _returnInter = new int[2];
           Hashtable _hash = new Hashtable();
           for(int i =0;i< nums.Length; i++)
            {
                _returnInter[0] = i;
                if(_hash.ContainsKey(target- nums[i]))
                {
                    _returnInter[1] = (int)_hash[target - nums[i]];
                    if(_returnInter[0]> _returnInter[1])
                    {
                        return new int[2] { _returnInter[1], _returnInter[0] };
                    }
                    return _returnInter;
                }
                else
                {
                    if(!_hash.ContainsKey(nums[i]))
                    {
                        _hash.Add(nums[i], i);
                    }
                }
            }

            return null;
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_28962939/article/details/99543053
今日推荐