Pergunta de entrevista da empresa Amazon

implement the interface: interface SortedList<T>{ /*Get an item from list at index position *params index - index position in array *returns item - if item is found at index position *throws IndexOutOfBoundException - if input index is not within list T get(int index); } Check if an item exists in sortedList. Eg. 1,2,3,4,5,6 ...

Respostas da entrevista

Sigiloso

2 de mai. de 2017

var input = [1,2,3,4,5,6,7]; function findNumber(input, number) { if(input.length === 0) return false; if(input.length === 1 && input[0] === number) return true; if(input.length === 1 && input[0] !== number) return false; let pivot = 0; let middle; while(input.length > 1) { middle = Math.floor(input.length/2) pivot = input[middle]; if(pivot === number) return true; else{ if(number > pivot) { input = input.slice(middle+1); } else { input = input.slice(0, pivot); } } } return false; } findNumber(input, 6);

Sigiloso

12 de abr. de 2017

package com.foo; public class MyMain { public static void main(String[] args) { Integer [] arr = {1,2,3,4,5,6}; MySortedList sortedList = new MySortedList(arr); System.out.println("Result: "+sortedList.get(5)); } } interface SortedList{ T get(int index); } class MySortedList implements SortedList{ T [] arr; public MySortedList(T [] t){ this.arr = t; } public T get(int index){ if(index>arr.length-1){ throw new IndexOutOfBoundsException("requested index: "+ index); } return arr[index]; } }