LeetCode——1.两数之和

本文介绍了一种解决“两数之和”问题的算法,通过遍历整数数组找到和为目标值的两个整数,并返回它们的数组下标。使用Java实现,包括输入输出处理,适用于竞赛和实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

 

注:本分类博客中的所有代码可以直接拷贝到eclipise

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 
 *
 * @版权 : Copyright (c) 2017-2018 *********公司技术开发部
 * @author: gaozhenchao
 * @E-mail: 1226046769@qq.com
 * @版本: 1.0
 * @创建日期: 2019年1月23日 下午4:36:41
 * @ClassName Solution
 * @类描述-Description: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个
 *                   整数,并返回他们的数组下标。
 * @修改记录:
 * @版本: 1.0
 */
class Solution {
	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] == target - nums[j]) {
					return new int[] { i, j };
				}
			}
		}
		return null;
	}
}

public class MainClass {
	public static int[] stringToIntegerArray(String input) {
		input = input.trim();
		input = input.substring(1, input.length() - 1);
		if (input.length() == 0) {
			return new int[0];
		}

		String[] parts = input.split(",");
		int[] output = new int[parts.length];
		for (int index = 0; index < parts.length; index++) {
			String part = parts[index].trim();
			output[index] = Integer.parseInt(part);
		}
		return output;
	}

	public static String integerArrayToString(int[] nums, int length) {
		if (length == 0) {
			return "[]";
		}

		String result = "";
		for (int index = 0; index < length; index++) {
			int number = nums[index];
			result += Integer.toString(number) + ", ";
		}
		return "[" + result.substring(0, result.length() - 2) + "]";
	}

	public static String integerArrayToString(int[] nums) {
		return integerArrayToString(nums, nums.length);
	}

	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = in.readLine()) != null) {
			int[] nums = stringToIntegerArray(line);
			line = in.readLine();
			int target = Integer.parseInt(line);

			int[] ret = new Solution().twoSum(nums, target);

			String out = integerArrayToString(ret);

			System.out.print(out);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值