Although I am a student majoring in computer science, I have been busy with professional courses before, and I have not been able to really use these good programming websites to improve my algorithmic ability. After two years of college life, in the last year, I hope that I The programming ability has improved after going out for an internship, so I decided to write questions on the programming website in the future to improve my ability. I didn't expect that the first time I brushed the questions, I encountered a bottleneck. The question, I thought the right way, but I failed to write the code correctly. Then I copied other people's code in the discussion and ran it, and there was an error. Then I kept looking for the answer on the Internet, and finally solved this simple problem. Suddenly I feel that I am white. I have learned professional knowledge for two years, and writing this blog is just to remind myself that I should cherish the rest of my college time, otherwise I will really be eliminated. . . The title and code are attached below.
topic:
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Error analysis of the original code: that is, without adding class solution{} to enclose the core code inside.
Code:
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[j] == target - nums[i]) { return new int[] { i, j }; } } } throw new IllegalArgumentException("No two sum solution"); } }