zoukankan      html  css  js  c++  java
  • leetcode题1Two sum 练习

    题目为:

    给一个整数数组, 返回数组中的两数之和等于指定值的两数在数组中的下标.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
     
    public int[] TwoSum(int[] nums, int target) {
            int[] result=new int[2];//创建一个返回数组;
            
              for (int j = 0; j < nums.Length; j++)//{1,4,5,7,9,10};//{9,6,5,3,1,0}外层循环,传进的数组赋值
                {
                    for (int k = j+1; k < nums.Length; k++)//创建内层循环,内层循环主要是让temp[i]=target-nums[i];让temp[i]的值与数组nums[i]比自己大的元素比较看是否相等。
                    {
                        
                        if (target - nums[j] == nums[k])
                        {
                            
                            result[0] = j;//相等就记录该位置。
                            result[1] = k;//记录相等的位置。
                        }
                        
                    }
                }
    
    
                return result;
    }

    附上该例源码:

    namespace ConsoleApplication1
    {
        class addtwonum
        {
            public static void Main(string[] args)
            {
                int[] num = { 2, 4, 4, 4, 4, 10 };//{9,6,5,3,1,0}
                int[] result = getnum(num, 8);
                for (int i = 0; i < result.Length; i++)
                {
                    Console.WriteLine(result[i]);
                }
                Console.ReadLine();
            }
            //
            //{1,2,3,4,6} tagart =5
            //a[0]+a[3] ,a[1]+a[2] [0,3],[1,2]
            private static int[] getnum(int []nums,int tagart)
            {
                int[] result=new int[2];
                int[] temp=new int[nums.Length];
                //for (int i = 0; i < nums.Length; i++)
                //    temp[i] = tagart - nums[i];
                for (int j = 0; j < nums.Length; j++)//{2, 4, 4, 7, 9, 10};//{6,4,4,-1,-2,-3}|{7,5,5,2,0,-1}
                {
                    for (int k = j+1; k < nums.Length; k++)
                    {
                        //result[0] = j;
                        //result[1] = k;
                        if (tagart - nums[j] == nums[k])
                        {
                            //j = nums.Length - 1;
                            //k = nums.Length;
                            result[0] = j;
                            result[1] = k;
                        }
    
                    }
                }
    
    
                return result;
            }
    
        }
    }
  • 相关阅读:
    345. Reverse Vowels of a String
    344. Reverse String
    125. Valid Palindrome
    67. Add Binary
    28. Implement strStr()
    20. Valid Parentheses
    14. Longest Common Prefix
    670. Maximum Swap
    2017济南北大青鸟accp和学士后课程的真实情况
    2017济南北大青鸟accp和学士后课程的真实情况
  • 原文地址:https://www.cnblogs.com/Hackerman/p/5746510.html
Copyright © 2011-2022 走看看