Leetcode.problem1:Two Sum

版权声明:转载请注明出处 https://blog.csdn.net/lcpskk/article/details/81569061
  • Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
  • code
public int[] TwoSum(int[] nums, int target) {
        
        List<int> indexList = new List<int>();
            Hashtable hashTable = new Hashtable();
            for (int i = 0; i < nums.Count<int>(); i++)
            {
                if (hashTable.ContainsKey(target - nums[i]))
                {
                    indexList.Add((int)hashTable[target - nums[i]]);
                    indexList.Add(i);
                    break;
                }
                else if (!hashTable.ContainsKey(nums[i]))
                {
                    hashTable.Add(nums[i], i);
                }

            }
            return indexList.ToArray();
    }
  • 代码思路:O(n^2)的时间复杂度降为O(n)。第一次遍历是少不了的,第二次遍历查找target-num[i]的O(n)过程用哈希表快速查找某个数值以及相应的下标索引来代替,时间复杂度为O(1)。

猜你喜欢

转载自blog.csdn.net/lcpskk/article/details/81569061