Đây là đáp án cho bài toán:

public class Two_Sum {
	static int target = 9;
	static int[] nums = { 2, 7, 11, 15 };

	public static void main(String[] args) {
		twoSum(nums, target);
	}

	public static 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) {
					System.out.println("[" + i + " , " + j + "]");
					return new int[] { i, j };
				}
			}
		}
		return null;

	}

}

Với bài toán này chúng ta cần 2 vòng for để tìm được 2 số sao cho tổng của nó bằng với target, và khi tìm được thì return vị trí của 2 số đó.

Chúc các bạn thành công.

82 Replies to “[300 bài code thiếu nhi][Java] Bài toán Two Sum”

  1. What are you indicating, man? I know everyones got their own thoughts and opinions, but really? Listen, your web log is cool. I like the hard work you put into it, specifically with the vids and the pics. But, come on. Theres gotta be a better way to say this, a way that doesnt make it seem like most people here is stupid!

  2. Good post. I learn something more difficult on different blogs everyday. It would always be stimulating to read content material from different writers and follow a little one thing from their store. I’d favor to use some with the content on my blog whether you don’t mind. Natually I’ll offer you a link in your web blog. Thanks for sharing.

  3. ในปัจจุบันผู้คนต่างสืบหาความสบายสบายเกือบ 100 BIOGAMEBET พนันบอลออนไลน์ที่ตอบปัญหาคนภายในยุคนี้ที่สุด ด้วยเหตุว่าสามารถพนันตรงไหนก็ได้ เวลาไหนได้หมด ง่าย สะดวกสบาย ที่สำคัญที่สุดเป็นปลอดภัยมากๆ

  4. I blog quite often and I really thank you for your content. This article has truly peaked my interest. I’m going to bookmark your blog and keep checking for new information about once per week. I opted in for your Feed as well.

Leave a Reply