Pergunta de entrevista da empresa X

Given an array of unsorted numbers, find triplets that equal a specified sum.

Respostas da entrevista

Sigiloso

6 de ago. de 2015

public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("What number yo? "); int findSum = sc.nextInt(); HashSet theSet = new HashSet(); while(theSet.size()<1000){ theSet.add((int)(Math.random()*2000)); } Integer[] nums = theSet.toArray(new Integer[theSet.size()]); long start = System.currentTimeMillis(); boolean Notfound = true; int i = 0; int numsFound = 0; while(Notfound){ int x = i+1; // Arrayoutofboundindex here.. can be fixed.. if(x == nums.length - 1) Notfound = false; int f = nums[i]; //{1,34,4,56,6,56,7634,3,34,34} int s = nums[x]; //f = 1, s = 34 for(int o = x+1; o < nums.length;o++){ int testSum = f+s+nums[o]; if(testSum == findSum){ numsFound++; System.out.println(f+" + "+ s+" + "+nums[o] + " found "+numsFound); } } if(numsFound == 10)Notfound = false; // this is just to find 10 different combinations. i++; } long end = System.currentTimeMillis(); System.out.println("Time taken "+(end-start)+" ms"); } }

Sigiloso

6 de ago. de 2015

public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("What number yo? "); int findSum = sc.nextInt(); HashSet theSet = new HashSet(); while(theSet.size()<1000){ theSet.add((int)(Math.random()*2000)); } Integer[] nums = theSet.toArray(new Integer[theSet.size()]); long start = System.currentTimeMillis(); boolean Notfound = true; int i = 0; int numsFound = 0; while(Notfound){ int x = i+1; // Arrayoutofboundindex here.. can be fixed.. if(x == nums.length - 1) Notfound = false; int f = nums[i]; //{1,34,4,56,6,56,7634,3,34,34} int s = nums[x]; //f = 1, s = 34 for(int o = x+1; o < nums.length;o++){ int testSum = f+s+nums[o]; if(testSum == findSum){ numsFound++; System.out.println(f+" + "+ s+" + "+nums[o] + " found "+numsFound); } } if(numsFound == 10)Notfound = false; // this is just to find 10 different combinations. i++; } long end = System.currentTimeMillis(); System.out.println("Time taken "+(end-start)+" ms"); } }

Sigiloso

3 de abr. de 2016

public List> threeSum(int[] nums) { List> result = new ArrayList(); if(nums == null || nums.length 0 && nums[i] == nums[i - 1]) continue; // Skip same results int target = 0 - nums[i]; int j = i + 1, k = len - 1; while(j < k) { if(nums[j] + nums[k] == target) { result.add(Arrays.asList(nums[i], nums[j], nums[k])); while(j < k && nums[j] == nums[j + 1]) j++; // Skip same results while(j < k && nums[k] == nums[k - 1]) k--; // Skip same results j++; k--; } else if(nums[j] + nums[k] < target) { j++; } else { k--; } } } return result; }