LeetCode刷题记录Easy篇(1)

来源:互联网 发布:韩顺平javascript 编辑:程序博客网 时间:2024/05/16 05:29

个人知识记录自己做的leetcode代码,这是最简单的算法的解决,不喜勿喷,个人表示很菜,但是一直在努力,另外我的算法旨在做出结果,并未考虑到效率问题。

1.Two Sum

**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].
Subscribe to see which companies asked this question.**
Solution:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
for(int i=0;i

7.Reverse Integer

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.
Subscribe to see which companies asked this question.
Solution:
public class Solution {
public int reverse(int x) {
long y = 0;//用来判断是否越界
int z = 0;//返回的逆序
boolean flag = true;//标记是否为正数
if(x<0){
x = Math.abs(x);
flag = false;
}
while(x>0){
y = y*10+x%10;
x /= 10;
if((flag==true&&y>Integer.MAX_VALUE)){
y = 0;
break;
}
if((flag==false&&-y

9.Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.
Solution:
public class Solution {
public boolean isPalindrome(int x) {
if(x<0)
return false;
int div = 1;
int left = 0;
int right = 0;
while(x/div>=10){
div*=10;
}
while(x!=0){
right = x%10;
left = x/div;
if(right!=left)
return false;
x=x%div/10;//先去除最高位在去除最低位
div/=100;//少了两位数
System.out.println(right + ” ” + left);
}
return true;
}
}

1 0