leetcode [1] Two Sum

题目要求:

给定一个数组nums,然后再给定一个数字,找出数组中哪两个数字之和等于这个给定的数字。
例如:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

代码思路:

两层循环

  • 外层先找出一个数字,并记录当前的位置;求出目标数值和这个数值之差
  • 内层在剩余的数中,看有没有差这个数。

代码

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int i = 0;
        while(i<nums.length)
        {
            int cha = target - nums[i];
            //if(cha >= 0)
            //{
                result[0] = i;
                int j = i + 1;
                while(j<nums.length)
                {
                    if(nums[j] == cha)
                    {
                        result[1] = j;
                        return result;
                        
                    }
                    j++;
                }
                
            //}
            i++;
        }
        return result;
    }
}

补充

刚开始的思路要判断差值是否大于0,并没有考虑到有负数出现的情况。

在考虑问题的时候一定要全面。整数还要包括负数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容