publicclassSolution{ publicintFindGreatestSumOfSubArray(int[] array){ int max=array[0]; int res=array[0]; for(int i=1;i<array.length;i++){ max=Math.max(max+array[i],array[i]); res=Math.max(res,max); } return res; } }
31.整数中1出现的次数
求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
1 2 3 4 5 6 7 8 9 10 11
publicclassSolution{ publicintNumberOf1Between1AndN_Solution(int n){ int count=0; for(int m=1;m<=n;m*=10){ int a=n/m; int b=n%m; count+=(a+8)/10*m+(a%10==1?b+1:0); } return count; } }
publicclassSolution{ publicbooleanFind(int target, int [][] array){ int m = array.length; if(m == 0) { returnfalse; } int n = array[0].length; int i = m - 1; int j = 0; while (i >= 0 && j < n) { if (array[i][j] == target) { returntrue; } elseif(array[i][j] > target) { i--; } else { j++; } } returnfalse; } }
2. 替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution{ public String replaceSpace(StringBuffer str){ String s = str.toString(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' ') { sb.append("%20"); } else { sb.append(s.charAt(i)); } } return sb.toString(); } }
3. 从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
1 2 3 4 5 6 7 8 9 10
publicclassSolution{ public ArrayList<Integer> printListFromTailToHead(ListNode head){ ArrayList<Integer> res = new ArrayList<>(); while (head != null) { res.add(0,head.val); head = head.next; } return res; } }
publicintserach(String txt){ int m=pat.length(); int n=txt.length(); int j=0; for (int i = 0; i < n; i++) { j=dp[j][txt.charAt(i)]; if(j==m){ return i-m+1; } } return -1; }