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

  click to show spoilers.

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.

click to show spoilers.

Some hints:

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  先要明白罗马数字的含义,如题很简单。

 No5
Write a function to find the longest common prefix string amongst an array of strings.
 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循环更优。

No7: 

  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;
}

  

 

LeeCode的更多相关文章

  1. leecode系列--Two Sum

    学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...

  2. insertion Sort List (链表的插入排序) leecode java

    逻辑简单,代码难写,基础不劳,leecode写注释不能出现中文,太麻烦,我写了大量注释,链表问题最重要的就是你那个指针式干啥的 提交地址https://oj.leetcode.com/problems ...

  3. 后续遍历 java leecode

    以前觉得后续遍历最难写,今天看了篇博客http://blog.csdn.net/sgbfblog/article/details/7773103,其实却是我们仔细比较后续遍历和先序遍历,其实后续遍历就 ...

  4. 非递归实现先序遍历 java leecode 提交

    写完才知道自己学习都是似是而非啊,大家可以也在leecode上提交代码,纯手写,离开eclipse第一种方式:数据结构书上的,使用栈大概思路.1.不断将根节点的左孩子的左孩子直到为空,在这个过程入栈. ...

  5. leecode 归并排序 链表(java)

    写了好久,终于写成了.第一次zai leecode错题,题目质量很高,适合面试,与 1.归并排序是稳定的,在java中 Arrays.sort(a);中对于对象的排序就是归并排序.对于原子类型数据使用 ...

  6. leecode第五百五十七题(反转字符串中的单词 III)

    class Solution { public: string reverseWords(string s) { string res; stack<char> sta; string:: ...

  7. leecode第二天-使用异或找出数组中的非重复元素

    leecode题目描述如下: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 思路: 最开始想到的是使用排序,排序之后就很容易找到非重复元素了. ...

  8. leecode第七十题(爬楼梯)

    class Solution { public: int climbStairs(int n) { vector<unsigned long long> num;//斐波那契数列 num. ...

  9. leecode第四十六题(全排列)

    class Solution { public: vector<vector<int>> permute(vector<int>& nums) { int ...

  10. leecode第五题(最长回文子串)

    class Solution { public: string longestPalindrome(string s) { int len = s.length(); || len == ) retu ...

随机推荐

  1. ASP.NET MVC5 Forms登陆+权限控制(控制到Action)

    一.Forms认证流程 请先参考如下网址: http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html 本文主要介绍使用自定义的身份认 ...

  2. bootstrap表格 之多选数据的获取

    使用表格的时候经常会用到多选的功能,比较常用,下面写一个小Dome记录一下 如下:单击批量删除按钮之后,需要获取选中行数据,传值到后台进行处理 一.获取选择行的数据 btnplDel是按钮id:tab ...

  3. C#微信公众号——消息处理

    ​当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL. 一.接收POST请求,处理XML信息 public void ProcessRequest(HttpC ...

  4. websocketj--随时随地在Web浏览器中操作你的服务端程序

    0 - 有没有觉得Linux标准终端界面输入输出枯燥无味? 1 - 什么?vmstat命令的输出数据不直观?有没有想过能够可视化该命令的输出? 2 - 尝试过用浏览器操作Windows中的cmd吗? ...

  5. mybatis的generator中xml配置问题

    <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.sung.risk.model.biz" t ...

  6. C#使用Gecko实现浏览器

    Gecko就是火狐浏览器的内核啦,速度很快,兼容性比.net内置的webbrowser高到不知哪里去了. 使用Gecko首先要下载一堆依赖库,主要是Skybound.Gecko和xulrunner. ...

  7. [Linux]使用awk批量杀进程的命令

    碰到需要杀掉某一类进程的时候,如何批量杀掉这些进程,使用awk命令是很好的选择. ps -ef|grep aaa|grep -v grep|awk '{print "kill -9 &quo ...

  8. SQL基础-----DDL

    1 (My)SQL入门 这里用了(My)SQL这样的标题,目的是介绍标准SQL的同时,也将MySQL在标准SQL上的扩展一同介绍给读者. 2:SQL分类 SQL语句主要可以划分为以下3个类别 .DDL ...

  9. 【转】如何使用slave_exec_mode优雅的跳过1032 1062的复制错误

    今天线上的主从复制发生1062的错误,使用sql_slave_skip_counter跳过之后,由于后面的事务需要对刚刚的数据进行update,后续造成了新的1032的错误. 后来,无意中发现还有更好 ...

  10. 知物由学 | 基于DNN的人脸识别中的反欺骗机制

    "知物由学"是网易云易盾打造的一个品牌栏目,词语出自汉·王充<论衡·实知>.人,能力有高下之分,学习才知道事物的道理,而后才有智慧,不去求问就不会知道."知物 ...