LeetCode刷题(Two Sum)

功能:Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

鉴于自己初学Java,如Map、list等功能还未学习,只给出以下最简单的解决办法。(性能可能并不优秀)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result= new int[2];
        for(int x=0;x<nums.length;x++)
           {
               inner:for(int y=x+1;y<nums.length;y++)
                    {
                         if((target-nums[x])==nums[y]) //判断当目标数减去外循环角标对应元素与内循环对应角标元素相同,即找到两加数。
                              {
                                   result[0]=x;
                                   result[1]=y;
                                   break;//找到第一组符合数据后跳出外循环
                              }
                    } 
               
            }
        return result;
    }
}

输入:[1,2,4,4]

             6

输出结果:[1,2]

可将此程序优化,修改为找出所有解,并返回所有解。

程序待给出。


当输入:[1,2,4,4]时,理论上有两个解[1,2]和[1,3]

程序修改为

class  Demo
{
	public static void main(String[] args) 
	{
		int[] arrs = {1,2,4,4};
		int target = 6;
		Solution a = new Solution();
        a.twoSum(arrs,6);

	}
}

class Solution
{

        public static void twoSum(int[] nums, int target) {  
		int n = nums.length;
		int N = n*(n-1)/2;
        int[][] result= new int[N][2];  
		int i=0;
            for(int x=0;x<nums.length;x++)  
               {  
                   for(int y=x+1;y<nums.length;y++)  
                        {  
                             if((target-nums[x])==nums[y]) //判断当目标数减去外循环角标对应元素与内循环对应角标元素相同,即找到两加数。  
                                  {  
                                       result[i][0]=x;  
                                       result[i++][1]=y;  
                                  }
			     else 
				  {
				       result[i][0]=0;  
                                       result[i++][1]=0;
				  }
                        }   
                     
                }  
	     for (int z=0;z<N ;z++ )
			{
	                       for(int c=0;c<2;c++)
				{
                                    if (c!=1)
                                      {
                                           System.out.print(result[z][c]+","); 
                                      }                              
                                     else  System.out.print(result[z][c]);
 } System.out.println();} } }


输出结果:0,0

                    0,0

                    0,0

                    1,2

                    1,3

                    0,0

程序可继续优化
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值