No1.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
个人LOW B代码:
public static int[] twoSum(int[] numbers, int target){
int []arr=new int[2];
for(int i=0;i<numbers.length;i++){
for(int j=numbers.length-1;j>=0;j--){
if(numbers[i]+numbers[j]==target){
arr[0]=i;
arr[1]=j;
return arr;
}
}
}
return arr; }
较好代码:
public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i);
}
return result;
}
较好代码简化版:
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; map.put(numbers[i], i))
if (map.containsKey(target - numbers[i]))
return new int[]{map.get(target - numbers[i]),i};
return new int[]{0,0};
}
}
No1 总结:个人代码,是从第一个数组元素开始查起 直到查不到,而较好代码是查询相距最近且总和为target的结果,且后者时间复杂度为O(n)==》仅限于JAVA中,C++可能是lgn, 较好代码有个bug,就是数组中有相同元素,因为map的缘故,所以排列在后面的元素会覆盖前面的元素来作为key存放到
map中,所以显示会出现同一个位置 如[3,3,2,4] 输出为1,1 No2.
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
public static int reverse(int x) {
int result=0; while(x!=0){
int tail=x%10;//123 3
int newResult=result*10+tail;
if(result!=(newResult-tail)/10){//内存溢出处理
return 0;
}
result=newResult;
x/=10;
}
return result;
}
No3.
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
public static boolean isPalindrome(int x) {//判断整数是否是回文 121 1221 均是回文
//能被10整除不是回文,注意0%10==0;排除0的可能,且负数没有回文
if(x%10&&x!=0==0||x<0){
return false;
}
int rev=0;
while(x>rev){
rev=rev*10+x%10;
x/=10;
} return (x==rev)||(x==(rev/10));//回文整数为偶数个或奇数个
}
No3总结: 判断整数回文 以后注意 奇偶数回文,相应的判断(return (x==rev)||(x==(rev/10));//回文整数为偶数个或奇数个)。要摒弃自己曾想用数组的方法,太LOW。
No4
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字转换成int
public int romanToInt(String s) {
int nums[]=new int[s.length()];
for(int i=0;i<s.length();i++){
switch (s.charAt(i)){
case 'M':
nums[i]=1000;
break;
case 'D':
nums[i]=500;
break;
case 'C':
nums[i]=100;
break;
case 'L':
nums[i]=50;
break;
case 'X' :
nums[i]=10;
break;
case 'V':
nums[i]=5;
break;
case 'I':
nums[i]=1;
break;
}
}
int sum=0;
for(int i=0;i<nums.length-1;i++){//先判断是否小于,因为无论>还是<都不包含 = 所以当VII这种情况,只能先判断sum-=nums[i]; 否则就会出现VII中II应该是相加而判断成相减
if(nums[i]<nums[i+1])
sum-=nums[i];
else
sum+=nums[i];
}
return sum+nums[nums.length-1];
}
方法2:
public static int romanToInt(String sst) {
int[] a = new int[26];
a['I' - 'A'] = 1;
a['V' - 'A'] = 5;
a['X' - 'A'] = 10;
a['L' - 'A'] = 50;
a['C' - 'A'] = 100;
a['D' - 'A'] = 500;
a['M' - 'A'] = 1000;
char prev = 'A';
int sum = 0;
for(char s : sst.toCharArray()) {
if(a[s - 'A'] > a[prev - 'A']) {
sum = sum - 2 * a[prev - 'A'];
}
sum = sum + a[s - 'A'];
prev = s;
}
return sum;
}
No4:VII 5+2=7 先要明白罗马数字的含义,如题很简单。
public static String longestCommonPrefix(String[] strs) {'
StringBuilder result=new StringBuilder();
if(strs!=null&&strs.length>0){//String数组引用不为空或数组有值
Arrays.sort(strs);
char[] start=strs[0].toCharArray();
char[] end=strs[strs.length-1].toCharArray();
for(int i=0;i<strs[0].length();i++){
if(end.length>i&&start[i]==end[i]){
result.append(start[i]);
}else {
return result.toString();
}
}
} return result.toString(); }
No5总结:①Arrays.sort排序 是按字典序排列 所以可能是 abc abccccccccccccccc abcd 并不是按长度排列,所以判断的时候需要特殊注意。
②可能存在数组越界,需要判断是否为空,和末尾end数组是否比i大 ,小则比较不了
No6
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
public static boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
for(char c:s.toCharArray()){
if(c=='{'){
stack.push('}');
}else if(c=='['){
stack.push(']');
}else if(c=='('){
stack.push(')');
}else if(stack.isEmpty()||stack.pop()!=c){
return false;
}
}
return stack.isEmpty(); }
No6:利用循环和Stack特性,每遍历一个 {【( 符号就push }】) 最后 再判断pop是否对应正确,最后返回isEmpty()
本解用到foreach循环, 而普通for循环和foreach循环区别(http://blog.csdn.net/mlc1218559742/article/details/52712408) 用ArrayList(数组)时普通for循环更优,而对于LinkList(List)foreach更优。本题是普通for循环更优。
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
public int strStr(String haystack, String needle) {
if(haystack.length()<needle.length()){
return -1;
}else if(needle.length()==0){
return 0;
}
if(haystack.contains(needle)){ return haystack.indexOf(needle); } return -1;
}