Pergunta de entrevista da empresa Salesforce

the second step was to write a function that would detect if a sorted array contains two integer that sum up to 7. And then improve your code so that the array is accessed with only one iteration.

Respostas da entrevista

Sigiloso

15 de ago. de 2012

The key to this question is that the array is already sorted. So while the previous answer would work, it doesn't take advantage of this fact. We set a pointer at each end of the array and sum the two values. If it's higher than our target value, we decrease the higher pointer. If it's lower, we increase the lower pointer. This gets you closer and closer to your target value. The basic algorithm below (where num is the target number, which could be 7). public static boolean addToNum(int num, int[] numList){ int i=0, j=numList.length-1; while(i!=j){ int numsAdded = numList[i]+numList[j]; if(numsAdded==num) return true; else if(numsAdded>num) j--; else if (numsAdded

6

Sigiloso

3 de abr. de 2011

Boolean findPaire(List l) { Set s = new TreeSet(); for (Integer t : l) { if (s.contains(7-t)) { return true; } s.add(t); } return false; }

4