题目一

原题链接 https://leetcode-cn.com/problems/two-sum/

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [, , , ], target = 

因为 nums[] + nums[] =  +  =
所以返回 [, ]

提示:不能自身相加。

测试用例

[,,,]
预期结果
[,]

格式模板

public class Solution {
public int[] TwoSum(int[] nums, int target) {
    /*
    代码
    */
}
}

笔者的代码,仅供参考

使用暴力方法,运行时间 700ms-1100ms

public class Solution {
public int[] TwoSum(int[] nums, int target) {
int [] a = new int[];
for (int i = ; i < nums.Length - ; i++)
{
for (int j = i + ; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
a[] = i;
a[] = j;
}
}
}
return a;
}
}

运行时间 400ms-600ms

由于使用的是哈希表,所以缺点是键不能相同。

public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] a = new int[];
System.Collections.Hashtable hashtable = new System.Collections.Hashtable();
for(int i = ; i < nums.Length; i++)
{
hashtable.Add(nums[i], i);
}
for(int i = ; i < nums.Length; i++)
{
int complement = target - nums[i];
if (hashtable.ContainsKey(complement) && int.Parse(hashtable[complement].ToString())!=i)
{
a[] = i;
a[] = int.Parse(hashtable[complement].ToString());
}
}
return a;
}
}

还是哈希表,缺点是哈希表存储的类型是object,获取值时需要进行转换。

        public int[] TwoSum(int[] nums, int target)
{
int[] a = new int[];
System.Collections.Hashtable h = new System.Collections.Hashtable();
for (int i = ; i < nums.Length; i++)
{
int c = target - nums[i];
if (h.ContainsKey(c))
{
a[] = int.Parse(h[c].ToString()) <= nums[i] ? int.Parse(h[c].ToString()) : i;
a[] = int.Parse(h[c].ToString()) > nums[i] ? int.Parse(h[c].ToString()) : i;
}
else if (!h.ContainsKey(nums[i]))
{
h.Add(nums[i], i);
}
}
return a;
}

抄一下别人的

public class Solution
{
public int[] TwoSum(int[] nums, int target)
{
int[] res = {, };
int len = nums.Length;
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = ; i < len; i++)
{
int query = target - nums[i];
if (dict.ContainsKey(query))
{
int min = (i <= dict[query]) ? i : dict[query];
int max = (i <= dict[query]) ? dict[query] : i;
return new int[] { min, max };
}
else if (!dict.ContainsKey(nums[i]))
{
dict.Add(nums[i], i);
}
} return res;
}
}
---------------------
作者:Bruce-Yeung
来源:CSDN
原文:https://blog.csdn.net/lzuacm/article/details/80551669
版权声明:本文为博主原创文章,转载请附上博文链接!

题目二

原题地址https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出:
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 。

示例 2:

输入: "bbbbb"
输出:
解释: 因为无重复字符的最长子串是 "b",所以其长度为 。

示例 3:

输入: "pwwkew"
输出:
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 。

要注意字符串为空、变量为null、字符串长度 Length = 1 等情况。

测试实例

输入
" "
"au"
"abcabcbb"
"bbbbb"
"pwwkew"
"aab" 预期结果分别是 1,2,3,1,3,2

代码格式模板

public class Solution {
public int LengthOfLongestSubstring(string s) { }
}

笔者的代码仅供参考

使用最笨的方式,200ms左右

public class Solution {
public int LengthOfLongestSubstring(string s) {
if (s == null || s == "")
return ; char[] a = s.ToCharArray(); //字符串转为字符数组
int start = ; //区间开始位置
int stop = ; //区间结束位置
int newMax = ; //当前区间数
int max = ; //区间最大个数 for (stop = ; stop < a.Length; stop++) //每次向后移动一位
{
bool b = false; //是否存在重复
for (int i = start; i < stop; i++) //检查当前元素在区间是否有相同值
{
if (a[stop] == a[i]) //如果stop+1位在区间找到相同的字符
{
char ls = a[stop];
if (newMax > max) max = newMax;
start = i + ; //区间开始位置重置
newMax = stop - start + ;
b = true;
break;
}
}
if (b == false)
newMax += ;
}
if (newMax > max) max = newMax;
return max;
}
}

完整测试代码(控制台)

using System;

namespace ConsoleApp1
{
public class Testa
{
public int LengthOfLongestSubstring(string s)
{
if (s == null || s == "")
return ; char[] a = s.ToCharArray(); //字符串转为字符数组
int start = ; //区间开始位置
int stop = ; //区间结束位置
int newMax = ; //当前区间数
int max = ; //区间最大个数 for (stop = ; stop < a.Length; stop++) //每次向后移动一位
{
bool b = false; //是否存在重复
for (int i = start; i < stop; i++) //检查当前元素在区间是否有相同值
{
if (a[stop] == a[i]) //如果stop+1位在区间找到相同的字符
{
char ls = a[stop];
if (newMax > max) max = newMax;
start = i + ; //区间开始位置重置
newMax = stop - start + ; //重新设置区间数
b = true;
break;
}
}
if (b == false) ////没有重新设置区间数时加1
newMax += ;
}
if (newMax > max) max = newMax;
return max;
}
}
class Program
{ static void Main(string[] args)
{
Testa t1 = new Testa(); //正确结果
Console.WriteLine(t1.LengthOfLongestSubstring(" ")); //
Console.WriteLine(t1.LengthOfLongestSubstring("au")); //
Console.WriteLine(t1.LengthOfLongestSubstring("abcabcbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("bbbbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("pwwkew")); //
Console.WriteLine(t1.LengthOfLongestSubstring("aab")); //
Console.ReadKey();
}
}
}

使用哈希集合,速度更快,100ms-150ms

        public int LengthOfLongestSubstring(string s)
{
int n = s.Length;
HashSet<char> set = new HashSet<char>(); //集合
int ans = , start = , stop = ; //ans为字符串长度,starp区间起点,stop区间终点
while (start < n && stop < n)
{
// try to extend the range [i, j]
if (!set.Contains(s[stop]))
{
set.Add(s[stop++]);
ans = Math.Max(ans, stop - start);
//或者ans = ans > (stop - start) ? ans : (stop - start)
}
else
{
set.Remove(s[start++]);
}
}
return ans;
}

完整控制台测试代码

using System;
using System.Collections.Generic;
using System.Linq; namespace ConsoleApp2
{
public class Solution
{
public int LengthOfLongestSubstring(string s)
{
int n = s.Length;
HashSet<char> set = new HashSet<char>(); //集合
int ans = , start = , stop = ; //ans为字符串长度,starp区间起点,stop区间终点
while (start < n && stop < n)
{
// try to extend the range [i, j]
if (!set.Contains(s[stop]))
{
set.Add(s[stop++]);
ans = Math.Max(ans, stop - start);
//或者ans = ans > (stop - start) ? ans : (stop - start)
}
else
{
set.Remove(s[start++]);
}
}
return ans;
}
}
class Program
{
static void Main(string[] args)
{ Solution t1 = new Solution(); //正确结果
Console.WriteLine(t1.LengthOfLongestSubstring(" ")); //
Console.WriteLine(t1.LengthOfLongestSubstring("au")); //
Console.WriteLine(t1.LengthOfLongestSubstring("abcabcbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("bbbbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("pwwkew")); //
Console.WriteLine(t1.LengthOfLongestSubstring("aab")); //
Console.ReadKey();
}
}
}

C# 算法题系列(一) 两数之和、无重复字符的最长子串的更多相关文章

  1. Newtonsoft.Json C# Json序列化和反序列化工具的使用、类型方法大全 C# 算法题系列(二) 各位相加、整数反转、回文数、罗马数字转整数 C# 算法题系列(一) 两数之和、无重复字符的最长子串 DateTime Tips c#发送邮件,可发送多个附件 MVC图片上传详解

    Newtonsoft.Json C# Json序列化和反序列化工具的使用.类型方法大全   Newtonsoft.Json Newtonsoft.Json 是.Net平台操作Json的工具,他的介绍就 ...

  2. 算法练习之合并两个有序链表, 删除排序数组中的重复项,移除元素,实现strStr(),搜索插入位置,无重复字符的最长子串

    最近在学习java,但是对于数据操作那部分还是不熟悉 因此决定找几个简单的算法写,用php和java分别实现 1.合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两 ...

  3. C++双指针滑动和利用Vector实现无重复字符的最长子串—力扣算法

    题目: 力扣原题链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ 给定一个字符串, ...

  4. leetcode刷题第三天<无重复字符的最长子串>

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 : 输入: "abcabcbb" 输出: 解释: 因为无重复字符的最长子串是 . 示例 : 输入: &quo ...

  5. LeetCode刷题--无重复字符的最长子串(中等)

    题目描述: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 " ...

  6. LeetCode 第 3 题:无重复字符的最长子串(滑动窗口)

    LeetCode 第 3 题:无重复字符的最长子串 (滑动窗口) 方法:滑动窗口 滑动窗口模板问题:右指针先走,满足了一定条件以后,左指针向前走,直到不满足条件. 特点:左右指针的方向是一致的,并且是 ...

  7. LeetCode 第三题--无重复字符的最长子串

    1. 题目 2.题目分析与思路 3.思路 1. 题目 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3 ...

  8. Java算法练习——无重复字符的最长子串

    题目链接 题目描述 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 1 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 &qu ...

  9. leetcode刷题3.无重复字符的最长子串

    题目:给定一个字符串,找出不含有重复字符的 最长子串 的长度. 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3. ...

随机推荐

  1. Golang 并发Groutine详解

    概述 1.并行和并发 并行(parallel):指在同一时刻,有多条指令在多个处理器上同时执行. 并发(concurrency):指在同一时刻只能有一条指令执行,但多个进程指令被快速的轮换执行,使得在 ...

  2. c#基础学习(0706)之使用虚方法实现多态

    使用虚方法实现多态 namespace _0706 { class Program { static void Main(string[] args) { //这个时候调用的是父类的方法 Person ...

  3. secureCRT的文件上传技巧

    现在我们经常会习惯性的使用windows系统,但现在开发项目和维护中经常都在使用linux服务器,以为它的性能更强.更精简. 学习大数据的同志们和维护后端的同志们,推荐一下secureCRT软件,用起 ...

  4. Spring 核心组件总结

    spring核心组件总结 spring介绍 spring概念 IOC: Inverse Of Control 控制反转 ​ 将我们创建对象的方式反转了,以前创建对象是由我们开发人员自己维护,包括依赖注 ...

  5. 撩课-Web大前端每天5道面试题-Day24

    1.下面的代码将输出什么? ; i < ; i++) { setTimeout(function() { console.log(i); }, i * ); } 闭包在这里能起什么作用? 上面的 ...

  6. struts2 上传下载文件,异常处理,数据类型转换

    一,web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=" ...

  7. lodop 二维码内容多少

    QRCode最多能放181个汉字:LODOP.ADD_PRINT_BARCODE(248,6,60,60,"QRCode","一二三四五六七八九十二二三四五六七八九十三二 ...

  8. git pull文件时和本地文件冲突的问题

    在使用git pull代码时,经常会碰到有冲突的情况,提示如下信息: error: Your local changes to 'c/environ.c' would be overwritten b ...

  9. python汉字转拼音

    上代码: #!/usr/bin/env python # -*- coding:utf-8 -*- """ Author:cleverdeng E-mail:clverd ...

  10. JS + jQuery 实现元素自动滚动到底部,兼容IE、FF、Chrome

    HTML代码: <ul class="tasklog-dialog-ul" id="auto_to_bottom"> <li>删除虚拟机 ...