1. 程式人生 > >關於第一次在LeetCode上刷題的一點心得

關於第一次在LeetCode上刷題的一點心得

雖然是計算機專業的學生,但是之前一直在忙著專業課的學習,沒能夠真正運用這些好的程式設計網站提升自己的演算法能力,過去了兩年的大學生活,在最後的一年時間裡,希望自己在出去實習程式設計能力有所提高,所以今晚開始就決定在今後的日子裡在程式設計網站上刷題,提高自己的能力,沒想到第一次在上面刷題就遇到了瓶頸,很簡單的一道題目,自己思路想對了,但是程式碼沒能寫對,然後在討論裡複製別人的程式碼過來執行也出現錯誤,然後一直在網上找答案,終於把這道簡單的題目解決了,突然覺得自己白學了兩年的專業知識,寫這篇部落格也只是用來提醒自己該好好珍惜剩下的大學時光了,不然真的會被淘汰。。。下面附上題目和程式碼。

題目:

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].

原始碼出錯解析:就是沒有加上class solution{}把裡面的核心程式碼圈住。

程式碼:

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");
}
}