zoukankan      html  css  js  c++  java
  • leetcode167

    public class Solution {
        public int[] TwoSum(int[] numbers, int target) {
            Dictionary<int, int> dic = new Dictionary<int, int>();
                int count = numbers.Count();
                List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
    
                for (int i = 0; i < count; i++)
                {
                    if (!dic.ContainsKey(numbers[i]))
                    {
                        dic.Add(numbers[i], i);
                        list.Add(new KeyValuePair<int, int>(numbers[i], i));
                    }
                }
    
                int[] ary = new int[2];
    
                for (int i = 0; i < list.Count; i++)
                {
                    for (int j = i; j < list.Count; j++)
                    {
                        var d1 = list[i];
                        var d2 = list[j];
                        if (d1.Key + d1.Key == target && d2.Value - d1.Value > 1)
                        {
                            ary[0] = d1.Value + 1;
                            ary[1] = d1.Value + 2;
                            return ary;
                        }
                        else if (i != j && d1.Key + d2.Key == target)
                        {
                            ary[0] = d1.Value + 1;
                            ary[1] = d2.Value + 1;
                            return ary;
                        }
                    }
                }
    
                return ary;
        }
    }

     https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/#/description

    补充一个“双指针”思想的解决方案,使用python实现:

     1 class Solution:
     2     def twoSum(self, numbers: 'List[int]', target: 'int') -> 'List[int]':
     3         i=0
     4         j=len(numbers)-1
     5         while numbers[i] + numbers[j] != target:
     6             if numbers[i] + numbers[j]>target:
     7                 j-=1
     8             else:
     9                 i+=1
    10 
    11         return [i+1,j+1]
  • 相关阅读:
    欧拉公式求四面体的体积
    欧拉公式求四面体的体积
    I
    I
    闭包传递(floyed)
    闭包传递(floyed)
    Python hypot() 函数
    Python cos() 函数
    Python atan2() 函数
    Python atan() 函数
  • 原文地址:https://www.cnblogs.com/asenyang/p/6732339.html
Copyright © 2011-2022 走看看