Two Sum Time Limit Exceeded


  • 0
    C

    Hi, I test leetcode first time,
    I want to resolve problems by myself,
    I see "Time Limit Exceeded" when I submit my code.
    can anyone help me to improve my code....?
    here's my java code:
    '''
    public class Solution {
    public int[] twoSum(int[] nums, int target) {
    List<Object> numList = new LinkedList<Object>();
    List<Object> compareList = new LinkedList<Object>();
    for(int i : nums) {
    numList.add(i);
    }
    int[] result = null;
    for(int num : nums) {
    int count = 0;
    result = new int[2];
    compareList = new ArrayList<Object>();
    compareList.addAll(numList);
    int tmp1 = target - num;
    int tmp2 = target - tmp1;
    if (compareList.contains(tmp1)) {
    int index = compareList.indexOf(tmp1);
    result[0] = index;
    compareList.add(index, new Object());
    compareList.remove(new Integer(tmp1));
    count++;
    }
    if (compareList.contains(tmp2)) {
    result[1] = compareList.indexOf(tmp2);
    count++;
    }
    if (result[0] != result[1] && count == 2) {
    break;
    }
    }
    Arrays.sort(result);
    return result;
    }
    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.