首页 / JAVA / LeetCode题解(C、JAVA)
LeetCode题解(C、JAVA)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了LeetCode题解(C、JAVA),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2163字,纯文字阅读大概需要4分钟。
内容图文
![LeetCode题解(C、JAVA)](/upload/InfoBanner/zyjiaocheng/729/0fb8ad335c194f5d9b231c1042da7716.jpg)
1 两数之和(Two Sum)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target)
{
int *res = (int*)malloc(sizeof(int)*2);
for(int i = 0;i < numsSize-1;i++)
{
for(int j = i+1;j < numsSize;j++)
{
if(nums[i]+nums[j] == target)
{
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for(int i = 0;i < nums.length;i ++)
{
m.put(nums[i], i);
}
for(int i = 0;i < nums.length;i ++)
{
int t = target - nums[i];
if(m.containsKey(t) && m.get(t) != i)
{
res[0] = i;
res[1] = m.get(t);
break;
}
}
return res;
}
}
7. 整数反转
class Solution {
public:
int reverse(int x)
{
long long res = 0;
while (x)
{
res = 10 * res + x % 10;
x /= 10;
}
return (res > INT_MAX || res < INT_MIN) ? 0 : res;
}
};
class Solution {
public int reverse(int x) {
long temp=0;
while(x!=0){
temp*=10;
temp+=x%10;
x/=10;
}
if(temp<Integer.MIN_VALUE || temp>Integer.MAX_VALUE)
return 0;
return (int)temp;
}
}
9. 回文数
bool isPalindrome(int x)
{
int reverse = 0;
int back = x;
if(x == 0)
return true;
if(x < 0 || x % 10 == 0)
return false;
while(x)
{
reverse = reverse * 10 + x % 10;
x /= 10;
}
return back == reverse;
}
class Solution {
public boolean isPalindrome(int x) {
int res = 0;
int tmp = x;
if(x < 0)
{
return false;
}
while(x != 0)
{
res = res*10 + x%10;
x /= 10;
}
return res == tmp ? true : false;
}
}
13. 罗马数字转整数
int romanToInt(char* s)
{
char *input = s;
int output = 0;
int i = 0;
while(i < strlen(input))
{
if(input[i] == 'I')
{
if(input[i+1] == 'V')
{
output += 4;
i += 2;
}
else if (input[i+1] == 'X')
{
output += 9;
i += 2;
}
else
{
output += 1;
i += 1;
}
}
if(input[i] == 'X')
{
if(input[i+1] == 'L')
{
output += 40;
i += 2;
}
else if (input[i+1] == 'C')
{
output += 90;
i += 2;
}
else
{
output += 10;
i += 1;
}
}
if(input[i] == 'C')
{
if(input[i+1] == 'D')
{
output += 400;
i += 2;
}
else if (input[i+1] == 'M')
{
output += 900;
i += 2;
}
else
{
output += 100;
i += 1;
}
}
if(input[i] == 'V')
{
output += 5;
i += 1;
}
if(input[i] == 'L')
{
output += 50;
i += 1;
}
if(input[i] == 'D')
{
output += 500;
i += 1;
}
if(input[i] == 'M')
{
output += 1000;
i += 1;
}
}
return output;
}
在这里插入代码片
内容总结
以上是互联网集市为您收集整理的LeetCode题解(C、JAVA)全部内容,希望文章能够帮你解决LeetCode题解(C、JAVA)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。