Simple O(n) java solution using ArrayList


  • 0
    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int result[] = new int[2];
            ArrayList<Integer>al=new ArrayList<Integer>();
            for(int i=0; i<nums.length;i++){
                if(!al.contains(nums[i])){
                  al.add(target-nums[i]);
                }
                else{
                    result[0]=al.indexOf(nums[i]);
                    result[1]=i;
                    break;
                }
            }
            return result;
        }
    }

Log in to reply
 

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