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. Nginx动静分离架构

    Nginx动静分离简单来说就将动态与静态资源分开,不能理解成只是单纯的把动态页面和静态页面物理分离,严格意义上说应该是动态请求跟静态请求分开,可以理解成使用Nginx处理静态页面,Tomcat,Res ...

  2. Linux入门:vi 和 vim

    vi编辑器是所有Unix及Linux系统下标准的编辑器,它的强大不逊色于任何最新的文本编辑器. 本文介绍了vi (vim)的基本使用方法,但对于普通用户来说基本上够了! 转自:http://www.l ...

  3. Linux知识积累(2)dirname的使用方法

    linux中的cd "$(dirname "$0")"/是什么意思呢? 分析如下: 1.$0 表示当前动行的命令名,一般用于shell 脚本中 2.dirnam ...

  4. redis入门(01)redis的下载和安装

    参考链接: 命令手册 : http://www.redis.net.cn/order/ 菜鸟教程: http://www.runoob.com/redis/redis-install.html 一.概 ...

  5. python入门(10)使用List和tuple

    python入门(10)使用List和tuple list Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素. 比如,列出班里所有同学的名字,就可 ...

  6. HTML中的上下标标签的演示

    HTML中的上下标标签的演示 #table_head>td { font-weight: bold } tr { text-align: center } 作用 标签 演示代码 呈现效果 上标 ...

  7. 蛋疼zipline安装

    比安装zipline更让人蛋疼的是,网上的教程没有一个是TM对的,真的是忍不住要吐血. 真的是一步一坑,一步一坑 安装环境: Windows7旗舰版,64位系统 python 版本3.5.3 我没有用 ...

  8. Hive:动静态分区

    http://hugh-wangp.iteye.com/blog/1612268 http://blog.csdn.net/opensure/article/details/46537969 使用静态 ...

  9. POJ-1789 Truck History---最小生成树Prim算法

    题目链接: https://vjudge.net/problem/POJ-1789 题目大意: 用一个7位的string代表一个编号,两个编号之间的distance代表这两个编号之间不同字母的个数.一 ...

  10. 笔记本电脑连wifi然后通过有线网口做桥接

    让你的笔记本电脑作为主机,台式机通过通过一根网线连接到你的笔记本,共享无线网络上网,可以进行如下操作: 1,先找跟网线将两台电脑连接. 2,打开win7自带的windows防火墙,此步在控制面板里可以 ...