LeeCode
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;
}
LeeCode的更多相关文章
- leecode系列--Two Sum
学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...
- insertion Sort List (链表的插入排序) leecode java
逻辑简单,代码难写,基础不劳,leecode写注释不能出现中文,太麻烦,我写了大量注释,链表问题最重要的就是你那个指针式干啥的 提交地址https://oj.leetcode.com/problems ...
- 后续遍历 java leecode
以前觉得后续遍历最难写,今天看了篇博客http://blog.csdn.net/sgbfblog/article/details/7773103,其实却是我们仔细比较后续遍历和先序遍历,其实后续遍历就 ...
- 非递归实现先序遍历 java leecode 提交
写完才知道自己学习都是似是而非啊,大家可以也在leecode上提交代码,纯手写,离开eclipse第一种方式:数据结构书上的,使用栈大概思路.1.不断将根节点的左孩子的左孩子直到为空,在这个过程入栈. ...
- leecode 归并排序 链表(java)
写了好久,终于写成了.第一次zai leecode错题,题目质量很高,适合面试,与 1.归并排序是稳定的,在java中 Arrays.sort(a);中对于对象的排序就是归并排序.对于原子类型数据使用 ...
- leecode第五百五十七题(反转字符串中的单词 III)
class Solution { public: string reverseWords(string s) { string res; stack<char> sta; string:: ...
- leecode第二天-使用异或找出数组中的非重复元素
leecode题目描述如下: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 思路: 最开始想到的是使用排序,排序之后就很容易找到非重复元素了. ...
- leecode第七十题(爬楼梯)
class Solution { public: int climbStairs(int n) { vector<unsigned long long> num;//斐波那契数列 num. ...
- leecode第四十六题(全排列)
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { int ...
- leecode第五题(最长回文子串)
class Solution { public: string longestPalindrome(string s) { int len = s.length(); || len == ) retu ...
随机推荐
- angluarjs2入门学习资源
http://www.runoob.com/angularjs2/angularjs2-tutorial.htmlhttps://segmentfault.com/a/1190000008423981 ...
- kubernetes入门(06)kubernetes的核心概念(3)
一.API 对象 API对象是K8s集群中的管理操作单元.K8s集群系统每支持一项新功能,引入一项新技术,一定会新引入对应的API对象,支持对该功能的管理操作.例如副本集Replica Set对应的A ...
- ELK学习总结(3-1)elk的基本查询
基本查询:内置条件 组合查询:组合基本查询 过滤:查询同时,通过filter筛选数据 准备工作 GET /library/books/_mget { "ids":["1 ...
- SpringCloud的服务网关zuul
演示如何使用api网关屏蔽各服务来源 一.概念和定义 1.zuul最终还是使用Ribbon的,顺便测试一下Hystrix断路保护2.zuul也是一个EurekaClient,访问服务注册中心,获取元数 ...
- C# 后台构造json数据
前后台传值一般情况下,都会用到json类型的数据,比较常见,但是每次用到的时候去网上找比较麻烦,所以自己记录一下,下次直接用. 构造的json串格式,如下: [{","name&q ...
- C#微信公众号——消息处理
当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL. 一.接收POST请求,处理XML信息 public void ProcessRequest(HttpC ...
- spring4——IOC之基于注解的依赖注入(DI )
spring容器对于Bean的创建和对象属性的依赖注入提供了注解的支持,让我们在开发中能够更加便捷的实现对象的创建和对象属性的依赖注入.一,对于Bean的创建spring容器提供了以下四个注解的支持: ...
- java中的引用类型的对象存放在哪里
根据上下文来确定.比如void func(){ Object obj = new Object();//这个obj在函数的栈里.}class Test{ private Object obj ...
- antd 主题色
如果是自己配置的reac项目,而非官方推荐的creat-react-app或者dva-cli等阿里自己开发的脚手架去引入antd,会有两个问题 第一,用babel-plugin-import设置sty ...
- tensorflow让程序学习到函数y = ax + b中a和b的值
今天我们通过tensorflow来实现一个简单的小例子: 假如我定义一个一元一次函数y = 0.1x + 0.3,然后我在程序中定义两个变量 Weight 和 biases 怎么让我的这两个变量自己学 ...