zoukankan      html  css  js  c++  java
  • [LeetCode][Python][C#]刷题记录 1. 两数之和

    第一次做发现很多小细节以前都没注意过,感觉还是蛮头疼的。

    题目:

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

    你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

    根据题目要求【你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。】

    所以我们的思路就有了,只要每次循环只遍历后面的就可以啦,这样结果就不会重复惹。

    上代码

    python

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            for i in nums:
               for j in range(nums.index(i) + 1, len(nums)):
                   if i + nums[j] == target:
                        list = [nums.index(i),j]
                        return(list)
    nums = [2, 7, 11, 15]
    target = 9
    a = Solution()
    print(a.twoSum(nums,target))

     c#

    (好久没用过了,如果有错误和更好的写法请评论提醒我QUQ)

    public class Program
        {
            public int[] TwoSum(int[] nums, int target)
            {
                for (int i = 0; i < nums.Length; i++)
                {
                    for (int j = i+1; j < nums.Length; j++)
                    {
                        if (nums[i] + nums[j] == target)
                        {
                            
                            return new int[] { i, j };
    
                        }
    
                    }
                }
                throw new ArgumentException();
            }
            static void Main(string[] args)
            {
                int[] nums = { 2, 7, 11, 15 };
                Program pro = new Program();
    
                int[] result = pro.TwoSum(nums, 9);
                Console.WriteLine("[{0},{1}]",result[0],result[1]);
                Console.ReadKey();
            }
        }
  • 相关阅读:
    OpenCL 获取Program信息
    匈牙利算法
    经常使用的webservice接口
    庞果网之高斯公式
    T4 生成实体和简单的CRUD操作
    zTree实现地市县三级级联报错(三)
    AlphaBlend
    cocos2d-x 3.0 事件处理
    rman多通道全备份脚本
    Linux下的简单好用的计算器bc
  • 原文地址:https://www.cnblogs.com/babydoll/p/9577357.html
Copyright © 2011-2022 走看看