携程后台3A代码
第一题:类似链表排序
public static ListNode partition(ListNode head, int m) { ListNode sB = null;// 小于等于m的链表起点 ListNode sE = null;//小于等于m的链表终点 ListNode bB = null; ListNode bE = null; ListNode next = null;//保存下一个节点 //进行划分 while (head != null) { next = head.next; head.next = null; if (head.val <= m) { if (sB == null) { sB = head; sE = head; } else { sE.next = head; sE = sE.next; } } else { if (bB == null) { bB = head; bE = head; } else { bE.next = head; bE = bE.next; } } head = next; } //串联 if (sB != null) { sE.next = bB; } return sB != null ? sB : bB; }第二题:反转字符串
static String resolve(String expr) { Stack<Character> stack = new Stack<>(); int t = 0;// 统计'('的个数 for(int i = 0; i < expr.length(); i++){ if(expr.charAt(i) == '('){ stack.push(expr.charAt(i)); t++; }else if(expr.charAt(i) != ')'){ stack.push(expr.charAt(i)); }else{ if(t < 1){ return ""; } // 开始旋转 StringBuilder builder = new StringBuilder(); while(stack.peek() != '('){ builder.append(stack.peek()); stack.pop(); } stack.pop(); t--; // 放进去 String s = builder.toString(); for(int j = 0; j < s.length(); j++){ stack.push(s.charAt(j)); } } } if(t != 0){ return ""; } char[] str = new char[stack.size()]; int i = stack.size() - 1; while(!stack.isEmpty()){ str[i--] = stack.peek(); stack.pop(); } return new String(str); }
第三题:任务调度,采用二分法
static int schedule(int m,int[] array) { int n = array.length; int max = 0; int sum = 0; for(int i = 0; i < n; i++){ max = Math.max(max, array[i]); sum += array[i]; } if(m >= n) return max; int target = bSearch(max, sum, m, array); return target; } static int bSearch(int lower, int upper, int m, int[] array){ int n = array.length; int mid = 0; while (lower <= upper){ mid = (lower + upper) >> 1; int curSum = 0; int count = 0; boolean flag = true; for(int i = 0; i < n;){ while (i < n && curSum + array[i] <= mid){ curSum += array[i++]; } count++; if(count > m){ flag = false; break; } curSum = 0; } // 是否可以继续缩小 if(flag){ upper = mid - 1; }else{ lower = mid + 1; } } return mid; }