java - I have an efficient algorithm to find the maximum integer in an array of millions, need advice on these two -
which better use array of millions of integers(ages)
public static int findmax(int[] x) { int max = 0; int curr = 0; (int : x) { curr = math.max(curr, a); max = math.max(max, curr); } return max; } public static int findmax(int[] x){ list<integer> list = new arraylist<>(); (int y : x){ list.add(y); } return collections.max(list); }
the first 1 faster second one, don't want making arraylist no reason find maximum of array!
also, there no reason use 2 different variables current , max, max suffice, so:
public static int findmax(int[] x) { int max = integer.min_value; (int : x) { max = math.max(max, a); } return max; }
note: used minimum integer because largest value in array may negative. also, use if-condition instead of math.max(), it'll work either way. saves operation. runtime o(n) in every case.
Comments
Post a Comment